类型'Any'在更新到Swift 3后没有下标成员 [英] Type 'Any' has no subscript members after updating to Swift 3

查看:137
本文介绍了类型'Any'在更新到Swift 3后没有下标成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在Swift中的代码:

$ p $ 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
})


$ b


Type'Any'没有下标成员


$ c> snapshot.value![在这里插入一些] 在我的代码的许多地方,我得到这个错误,我可以

以下代码可以工作:

 让pic =(snapshot.value as?NSDictiona ry)?[pictureURL]为?字符串? 

但是,我没有看到现在发生了什么变化,之前。



我所知道的唯一变化是观察的语法,但我不明白为什么这导致我的代码停止在 / interface_f_i_r_data_snapshotrel =noreferrer> FIRDataSnapshot value 类型为 id



Swift 3 中,在Firebase文档中,它表示任何



c $ c> value 可以是任何 NSDictionary NSArray NSNumber NSString - 显然,下标对所有这些都没有意义,特别是在Swift中。如果您知道这是一个 NSDictionary ,那么您应该将其转换为。


Here is my code in 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:

"Type 'Any' has no subscript members"

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.

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.

解决方案

In FIRDataSnapshot, value is of type id.

In Swift 3, id is imported as 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.

这篇关于类型'Any'在更新到Swift 3后没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆