简体   繁体   English

快速访问嵌套键/值对

[英]Accessing nested key-value pairs in swift

I am trying to access the value of the key 1. Here is my Firebase diagram: 我正在尝试访问键1的值。这是我的Firebase图:

在此处输入图片说明

And here is my code: 这是我的代码:

@IBAction func ridefinder(_ sender: Any) {

    let ref = Database.database().reference()
    ref.child("name/hi").observeSingleEvent(of: .value) { (snapshot) in
         print(snapshot.value as? [String:Any])
    }

When I run this it prints nil , however when I change it slightly to this: 当我运行它时,它显示nil ,但是当我将其稍微更改为:

@IBAction func ridefinder(_ sender: Any) {

    let ref = Database.database().reference()
    ref.child("name").observeSingleEvent(of: .value) { (snapshot) in
         print(snapshot.value as? [String:Any])
    }

it prints both sets of key-value pairs inside. 它在内部打印两组键值对。

How do I just access the value of the key hi inside name? 如何只访问name内部的hi关键字的值?

Try: 尝试:

let ref = Database.database().reference()
ref.child("name").observeSingleEvent(of: .value) { (snapshot) in
     if let value = snapshot.value as? [String:Any], let hi = value["hi"] as? String { 
         print(hi)
     }
}

Values inside database references are accessed by using snapshot.value and being casted as [String: Any]. 数据库引用内的值可以通过使用snapshot.value进行访问,并强制转换为[String:Any]。 And then you find your desired values inside dictionary like always accessing them as dictionary["key"]. 然后,您可以在字典中找到所需的值,就像始终将其作为dictionary [“ key”]进行访问一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM