ios 更新到 Swift 3 后,键入“Any”没有下标成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39480150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type 'Any' has no subscript members after updating to Swift 3
提问by user6820041
Here is my code in Swift:
这是我在 Swift 中的代码:
currentUserFirebaseReference.observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
let UID = snapshot.key
let pictureURL = snapshot.value!["pictureURL"] as! String
let name = snapshot.value!["displayname"] as! String
let currentUser = Person(name: name, bio: "", UID: UID, pictureURL: pictureURL)
self.currentUserInfo = currentUser
})
I just updated to Xcode 8 / Swift 3, which seems to have caused the following error message:
我刚刚更新到 Xcode 8 / Swift 3,这似乎导致了以下错误消息:
"Type 'Any' has no subscript members"
“类型‘Any’没有下标成员”
I call snapshot.value!["
insert something here"]
in many places in my code, I'm getting this error and I can't run my code.
我在我的代码中的很多地方调用了snapshot.value!["
insert something here "]
,我收到了这个错误,我无法运行我的代码。
The following code works:
以下代码有效:
let pic = (snapshot.value as? NSDictionary)?["pictureURL"] as? String ?? ""
However, I don't see what changed or what makes this necessary now versus how it was before.
但是,与以前相比,我看不出现在有什么变化或什么使这变得必要。
The only thing that has changed as far as I'm aware is the syntax of the observe, but I don't understand why this caused my code to stop working.
据我所知,唯一改变的是观察的语法,但我不明白为什么这会导致我的代码停止工作。
采纳答案by J. Cocoe
In FIRDataSnapshot, value
is of type id
.
在FIRDataSnapshot 中,value
类型为id
。
In Swift 3, id
is imported as Any
.
在Swift 3 中,id
导入为Any
.
In the Firebase documentation, it says value
can be any of NSDictionary
, NSArray
, NSNumber
, or NSString
-- clearly, subscripting doesn't make sense on all of these, especially in Swift. If you know it's an NSDictionary
in your case, then you should cast it to that.
在火力地堡文档,它说value
可以是任意的NSDictionary
,NSArray
,NSNumber
,或NSString
-显然,下标无厘头对所有这些,尤其是斯威夫特。如果您知道这是NSDictionary
您的情况,那么您应该将其转换为。
回答by Aylii
J. Cocoe's answer is absolutely correct, but for those who need a code example this is how you do it:
J. Cocoe 的回答是绝对正确的,但对于那些需要代码示例的人,您可以这样做:
instead of
代替
let name = snapshot.value!["displayname"] as! String
try
尝试
let snapshotValue = snapshot.value as? NSDictionary
let name = snapshotValue["displayName"] as? String
The idea is that you need to cast the type of snapshot.value from Any to an NSDictionary.
这个想法是您需要将 snapshot.value 的类型从 Any 转换为 NSDictionary。
Edit:
编辑:
As Connor pointed out, force unwrapping snapshot.value or anything from a backend system is a bad idea due to possibly receiving unexpected information. So you change as! NSDictionary to as? NSDictionary.
正如康纳指出的那样,由于可能会收到意外信息,因此强制解包 snapshot.value 或后端系统中的任何内容是一个坏主意。所以你改成!NSDictionary to as?NSD词典。