从 'CLLocation?' 向下转换为 'CLLocation' 只解包可选值;您是要使用“!”吗?
Downcast from 'CLLocation?' to 'CLLocation' only unwraps optionals; did you mean to use '!'?
我试图在地图视图上显示用户当前位置,但在位置管理器功能的第一行出现错误
这是我的代码
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?' 向下转换到 'CLLocation' 只解包选项;你是想使用 '!' 吗?[=13=]
上线让location=locations.lastas! CLLocation
您正在强制转换 Optional
CLLocation
到 CLLocation
,这就是为什么 Swift 建议简单地强制展开它:
let location = locations.last!
如果 locations
为空,这个版本(和你的)将会崩溃。
因此,我建议永远不要强行打开任何东西,而是使用 guard
:
guard let location = locations.last else {
return
}
我试图在地图视图上显示用户当前位置,但在位置管理器功能的第一行出现错误
这是我的代码
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?' 向下转换到 'CLLocation' 只解包选项;你是想使用 '!' 吗?[=13=]
上线让location=locations.lastas! CLLocation
您正在强制转换 Optional
CLLocation
到 CLLocation
,这就是为什么 Swift 建议简单地强制展开它:
let location = locations.last!
如果 locations
为空,这个版本(和你的)将会崩溃。
因此,我建议永远不要强行打开任何东西,而是使用 guard
:
guard let location = locations.last else {
return
}