在swift 3中键入任何没有下标错误

Posted

技术标签:

【中文标题】在swift 3中键入任何没有下标错误【英文标题】:Type any has no subscript error in 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 还很陌生,并且停留在这一点上。看到其他相关帖子,但我找不到解决方案。请帮忙。

【问题讨论】:

Edit 您的代码显示了如何声明和初始化 property Type 'Any' has no subscript members after updating to Swift 3的可能重复 当然你的答案可以在these search results中找到。 ... 另请注意:***.com/q/38956785/499581、***.com/q/39778940/499581、***.com/q/39576282/499581、***.com/q/39549107/499581 【参考方案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

【讨论】:

以上是关于在swift 3中键入任何没有下标错误的主要内容,如果未能解决你的问题,请参考以下文章

错误:键入 [AnyHashable: Any]?没有下标成员 (Swift)

在 swift 3 中打印 json 时出现任何下标成员错误 [重复]

Swift 中的“类型‘值’没有下标成员”错误

类型 Any 没有下标成员 Swift 3.0 中的错误?

任何对象?没有名为“下标”的成员 swift

类型“Any”没有下标成员/Swift 3 [重复]