![](/img/trans.png)
[英]SWIFT - Cannot assign value of type '[(String, [String : Any])]' to type '[String : [String : Any]]'
[英]Swift, get data from [String: Any] type value
我有這樣的價值;
["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
}
假設您的數據結構與您在頂部引用的內容相匹配,您應該能夠將第一行轉換為:
guard let data = snapshot.value as? [String:[String:Any]]
如果沒有,如果您打印snapshot.value
,t 將有助於查看控制台的外觀
然后,我之前的回答中的以下內容應該可以工作:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.