ios CLLocation didUpdateLocations错误

时间:2015-12-29 13:17:07

标签: ios swift cllocationmanager

我正在使用XCode7.2版本

我尝试使用locationManager委托函数

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
 let location = locations.last as! CLLocation
 print("%f/%f",location.coordinate.latitude,location.coordinate.longitude)

 }

但我收到以下错误:

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

我不知道如何解决这个问题。

快速代码更改

有谁可以帮我解决问题?

谢谢

1 个答案:

答案 0 :(得分:0)

locations.last返回类型为CLLocation?,因为数组可能根本没有元素。作为错误状态,您不必将可选类型强制转换为非可选类型,只需执行此操作即可解压缩它:

let location = locations.last!

请注意,使用上述方法可能会导致异常并始终考虑使用可选的展开

if let location = locations.last{
    print("%f/%f",location.coordinate.latitude,location.coordinate.longitude)
}