小编典典

类型“任何”没有下标成员

swift

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

我查看了以前的文章,但似乎找不到解决此问题的方法。所有三行代码都给出“类型’Any’没有下标成员”错误。对此还很陌生,因此不胜感激。


阅读 333

收藏
2020-07-07

共1个答案

小编典典

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

因此,这里发生的是,作为开发人员的YOU知道这snapshot.value是一个Dictionary,但是编译器却没有。它不会让您调用该subscript函数,因为您试图在type的值上调用它Any并且Any未实现subscript。为此,您必须告诉编译器您snapshot.value实际上是一个Dictionary。此外,还Dictionary可以让您将下标函数与Dictionary键的类型无关。因此,您需要告诉它您有一个Dictionary带有String(AKA
[String: Any])的键。会比这还要进一步,你的情况,你似乎知道,都在你的价值观DictionaryString一样,所以代替铸造每个值,你就下标后String使用as! String,如果只是告诉您同时Dictionary 具有两种String类型的键和值(AKA [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"]

在那里,您拥有了!

2020-07-07