我正在尝试在地图视图中显示用户当前位置,但我在位置管理器功能的第一行显示错误
这是我的代码
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)
}
}
我得到的错误是“来自'CLLocation的'Downcast?' 'CLLocation'只能打开选项;你的意思是使用'!'?
在线让location = locations.last为! CLLocation
答案 0 :(得分:0)
你强迫Optional
CLLocation
加注CLLocation
,这就是为什么斯威夫特建议只是强行打开它:
let location = locations.last!
如果locations
为空,则此版本(和您的版本)将崩溃。
因此,我建议永远不要强制打开任何内容,而是使用guard
代替:
guard let location = locations.last else {
return
}