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/