【问题标题】:Swift, get data from [String: Any] type valueSwift,从 [String: Any] 类型值获取数据
【发布时间】:2021-03-06 18:32:24
【问题描述】:

我有这样的价值观;

["id1": {
name = "iphone 6s";
price = 330;
}, "id2": {
    name = iphone7s;
    price = 500;
}]

我不知道 id 是什么。但我需要从该数据中获取名称和价格数据。

编辑:这是获取值代码;

database.child("SortedItems").child("byName").observeSingleEvent(of: .value, with: { snapshot in
        guard let value = snapshot.value as? [String: Any] else {
            return
        }

【问题讨论】:

  • 这个问题为什么要打上json标签,你有字典还是json消息?
  • 这是一本直​​截了当的字典,有什么问题吗?请显示您所做的任何代码尝试。

标签: arrays json swift


【解决方案1】:

假设您的数据结构与您在顶部引用的内容相匹配,您应该能够将第一行转换为:

guard let data = snapshot.value as? [String:[String:Any]]

如果没有,如果您打印snapshot.value,查看控制台的外观会很有帮助


那么,我之前的回答中的以下内容应该工作:

let ids = data.keys //get just the ids/keys

//iterate through and print the name and price once they're cast to the correct types
data.forEach { (key,value) in
    if let name = value["name"] as? String, let price = value["price"] as? Int {
        print(name)
        print(price)
    }
}

//declare a model type that conforms to Codable
struct Phone : Codable {
    var name : String
    var price : Int
}

data.forEach { (key, value) in
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: value, options: [])
//decode the Phone model 
        let phoneModel = try JSONDecoder().decode(Phone.self, from: jsonData)
        print(phoneModel)
    } catch {
        //handle error
    }
}

您可能还想查看 Firebase 文档,其中提供了有关获取数据的更多详细信息,包括转换为自定义对象:https://firebase.google.com/docs/firestore/query-data/get-data

【讨论】:

  • 嘿,我更新了问题。新增获取数据功能。我用改变值的数据编辑了你的代码。它给我一个错误,如果让 name = value["name"] as?字符串,让 price = value["price"] as?诠释 {
猜你喜欢
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 2023-01-10
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
相关资源
最近更新 更多