Search code examples
iosswiftcllocation

Downcast from 'CLLocation?' to 'CLLocation' only unwraps optionals; did you mean to use '!'?


I'm trying to display the users current location on a map view but I'm getting an error on the first line of the location manager function

Here is my code

import UIKit
import MapKit

class FirstViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var mapkitView: MKMapView!
var locationManager: CLLocationManager!

override func viewDidLoad()
{
    super.viewDidLoad()

    if (CLLocationManager.locationServicesEnabled())
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    let location = locations.last as! CLLocation

    let center = CLLocationCoordinate2DMake(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.mapkitView.setRegion(region, animated: true)
}
}

The error I'm getting is "Downcast from 'CLLocation?' to 'CLLocation' only unwraps optionals; did you mean to use '!'?

on line let location = locations.last as! CLLocation


Solution

  • You are force-casting an Optional CLLocationto CLLocation, that is why Swift suggests to simply force unwrap it:

    let location = locations.last!
    

    This version (and yours) will crash if locations is empty.

    Thus I recommend to never force unwrap anything and use guardinstead:

    guard let location = locations.last else {
        return
    }