【问题标题】:Swift 2.0 - Cannot Subscript a value of type '[CLPlacemark]?'Swift 2.0 - 无法为“[CLPlacemark] 类型的值下标?”
【发布时间】:2015-09-19 11:35:42
【问题描述】:

我正在尝试将我的 swift 1.2 应用程序转换为 2.0。我已经尝试了一些我在互联网上找到的修复方法,但它不起作用。

错误:Converting to Swift 2.0 - Cannot Subscript a value of type '[CLPlacemark]?'

代码:

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{

    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

        if (error != nil)
        {
            print("Error: " + error!.localizedDescription)
            return
        }

        if placemarks!.count > 0
        {
            let pm = placemarks[0] as! CLPlacemark
            self.displayLocationInfo(pm)
        }
        else
        {
            print("Error with the data.")
        }
    })
}

【问题讨论】:

    标签: swift2 xcode7


    【解决方案1】:

    已解决

    替换: let pm = placemarks[0] as! CLPlacemark

    对于: let pm = placemarks?[0]

    【讨论】:

      【解决方案2】:

      或者使用更新的 Swift 2.0 安全性:

      guard let currentPlacemarks = placemarks where currentPlacemarks.count > 0 else {
          // error handling here
          return
      }
      
      guard let pm = currentPlacemarks[0] where pm is CLPlacemark else {
          // more error handling
          return
      }
      
      self.displayLocationInfo(pm)
      

      【讨论】:

      • 我在尝试添加您的代码时收到以下错误。有什么想法吗? : 定义与先前的值冲突 条件绑定的初始化器必须具有可选类型,而不是 'CLPlacemark'
      • 这意味着它不是可选的,可选的绑定不起作用,不需要。谷歌所有选项
      • 会的。这很奇怪,因为我的代码与原始海报完全相同,所以我原以为它会被丢弃和替换。谢谢
      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多