swift - 类型 'Any' 没有下标成员

标签 swift swift3

let employerName = snapshot.value! ["employerName"] as! String
let employerImage = snapshot.value! ["employerImage"] as! String
let uid = snapshot.value! ["uid"] as! String

我查看了以前的帖子,但似乎找不到解决此问题的方法。所有三行代码都给出了“type 'Any' has no subscript members”错误。对此还很陌生,因此不胜感激。

最佳答案

snapshot.value 的类型是Any。下标是一种特殊的函数,它使用将值括在大括号中的语法。该下标函数由Dictionary实现。

所以这里发生的事情是,作为开发人员,您知道 snapshot.value 是一个 Dictionary,但编译器不知道。它不会让您调用 subscript 函数,因为您正试图在 Any 类型的值上调用它,而 Any 没有实现 下标。为此,您必须告诉编译器您的 snapshot.value 实际上是一个 Dictionary。此外,Dictionary 允许您将下标函数与 Dictionary 键的任何类型的值一起使用。因此,您需要告诉它您有一个 Dictionary,其键为 String(又名 [String: Any])。更进一步,在您的情况下,您似乎知道 Dictionary 中的所有值也是 String ,因此不要在下标之后强制转换每个值它到 String using as! String,如果您只是告诉它您的 Dictionary 具有都是 String 类型的键和值(又名 [String: String]),那么您将能够通过下标访问这些值,编译器也会知道这些值也是 String!

guard let snapshotDict = snapshot.value as? [String: String] else {
    // Do something to handle the error 
    // if your snapshot.value isn't the type you thought it was going to be. 
}

let employerName = snapshotDict["employerName"]
let employerImage = snapshotDict["employerImage"]
let uid = snapshotDict["fid"]

好了!

关于swift - 类型 'Any' 没有下标成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903204/

相关文章:

ios - 如果被拒绝,如何询问通知权限?

ios - '初始化()' is deprecated: init() will be removed in Swift 3. Use ` 零`

ios - 未调用 subview 手势识别器

Swift Firebase 如何停止进程?

ios - 为什么我不能将数字 append 到我的变量?!在 Swift 3 中

ios - 回调 swift 3 中的标签未更改

ios - 使用 Alamofire 4.0 (Swift 3) 下载文件

swift - 如何将一个复杂的抽象类移植到swift?

ios - 每天在特定时间重置特定值

ios - 使用 Alamofire 将对象作为参数发送