【问题标题】:type 'Any?' has no subscript members (using Firebase)输入“任何?”没有下标成员(使用 Firebase)
【发布时间】:2017-01-25 06:31:54
【问题描述】:

每次我运行这行代码时它都不起作用,任何可以帮助我的人也可以更改它吗?谢谢你的帮助。 :)

以下是我不断收到的错误

键入任何?没有下标成员

var ref:FIRDatabaseReference?
var refHandle: UInt!


var postData = [String]()

override func viewDidLoad() {

    super.viewDidLoad()



    ref = FIRDatabase.database().reference()
    refHandle = ref?.observe(FIRDataEventType.value, with:
    { (snapshot) in

        let dataDict = snapshot.value as! [String: AnyObject]

        print(dataDict)


    })

    let username: String = (FIRAuth.auth()?.currentUser?.uid)!

    ref?.child("Users").child(username).observeSingleEvent(of: .value, with:
    { (snapshot) in
        let username = snapshot.value!["Username"] as! String

        self.usernameField.text = username


    })

}

【问题讨论】:

    标签: ios swift3


    【解决方案1】:

    两个问题。

    1.可选

    这是 Swift 使变量处于两种状态之一的方式,即具有值或 nil。变量只能处于其中一种状态。您可以通过在变量前面添加问号来使变量成为可选变量。

    2。任意

    通过将变量声明为Any 类型,这意味着您没有在声明期间明确说明其类型。 Firebase 将其所有返回都设为 Any 类型,以便让我们的开发人员可以随意摆弄数据,从而减少对我们的限制。

    snapshot.value 的类型为 Any,但 Firebase 始终返回 JSON 树,并且 JSON 树可以表示为 Dictionaries。那我们该怎么办呢?

    1. 由于snapshot.value是可选的,我们应该先检查它是否是nil
    2. 如果不是nil,请将其转换为字典,然后开始访问其中的各个元素。

    下面的代码为您完成了这项工作,我添加了 cmets 来解释发生了什么。

    ref?.child("Users").child(username).observeSingleEvent(of: .value, with:
    { (snapshot) in
    
        // This does two things.
        // It first checks to see if snapshot.value is nil. If it is nil, then it goes inside the else statement then prints out the statement and stops execution.
        // If it isn't nil though, it converts it into a dictionary that maps a String as its key and the value of type AnyObject then stores this dictionary into the variable firebaseResponse.
    
        // I used [String:Any] because this will handle all types of data types. So your data can be Int, String, Double and even Arrays.
        guard let firebaseResponse = snapshot.value as? [String:Any] else
        {
            print("Snapshot is nil hence no data returned")
            return
        }
    
        // At this point we just convert the respective element back to its proper data type i.e from AnyObject to say String or Int etc
    
        let userName = firebaseResponse["Username"] as! String
    
        self.usernameField.text = username     
    })
    

    【讨论】:

    • Swift 3 本机 Dictionary 值类型为 Any so cast snapshot.value as? [String:Any]
    猜你喜欢
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多