类型any在swift中没有下标错误3

问题描述:

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版本时,我面临'Type any have no subscript error'。我对这个问题很敏感并且坚持不懈。看到其他相关的帖子,但没有我能找到解决方案。请帮忙。类型any在swift中没有下标错误3

+0

[编辑]你的代码显示property'如何'声明并初始化。 – rmaddy

+0

[Type'Any'在更新到Swift 3后没有下标成员](http://stackoverflow.com/questions/39480150/type-any-has-no-subscript-members-after-updating-to- swift-3) –

+1

当然你的答案可以在[这些搜索结果]中找到(http://stackoverflow.com/search?q=%5Bswift%5D+Type+any+has+no+subscript)。 – rmaddy

我倾倒了很多questions with duplicate titles,找不到明确涵盖您的案例,所以我将解释发生了什么。

您的变量property明确声明为Any,它是一个可以容纳任何类型的变量。错误消息告诉你,你不能使用它的下标[]。很显然,你相信它是一个Dictionary密钥String可以是任何东西。在Swift 3中,任何东西被键入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 
}