【问题标题】:Type any has no subscript error in swift 3在swift 3中键入任何没有下标错误
【发布时间】:2017-04-22 01:31:15
【问题描述】:
    if let name = property["Name"] as? String,
      let latitude = property["Latitude"] as? NSNumber,
      let longitude = property["Longitude"] as? NSNumber,
      let image = property["Image"] as? String {

      // To learn how to read data from plist file, check out our Saving Data
      // in iOS Video Tutorial series.

      // Code goes here


    }

当我将我的代码转换为当前的 swift 版本时,我面临“键入任何没有下标错误”。我对 swift 还很陌生,并且停留在这一点上。看到其他相关帖子,但我找不到解决方案。请帮忙。

【问题讨论】:

标签: ios swift


【解决方案1】:

我倾注了许多questions with duplicate titles 并找不到一个清楚地涵盖你的情况,所以我将解释发生了什么。

您的变量property 明确声明为Any 类型,这是一个可以容纳任何类型的变量。错误消息告诉您不能使用下标[]。很明显,您认为这是一个 Dictionary,其 keyString,而 value 可以是任何东西。在 Swift 3 中,anything 的类型为 Any。所以你的property 应该是[String : Any]。如果您将property 转换为[String : Any],那么您将能够使用[]

您应该做的第一件事是尝试将property 转换为[String : Any],然后如果可行则继续:

if let property = property as? [String : Any],
    let name = property["Name"] as? String,
    let latitude = property["Latitude"] as? NSNumber,
    let longitude = property["Longitude"] as? NSNumber,
    let image = property["Image"] as? String {

    // To learn how to read data from plist file, check out our Saving Data
    // in iOS Video Tutorial series.

    // Code goes here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2018-03-24
    相关资源
    最近更新 更多