如何在Swift 3中从字典中检索值 [英] How to retrieve a value from dictionary in Swift 3
问题描述
我具有从FireBase
获取用户并将其转换为Dictionary
的功能:
I have this function that fetch users from FireBase
and convert them in Dictionary
:
let leaderBoardDB = FIRDatabase.database().reference().child("scores1").queryOrderedByValue().queryLimited(toLast: 5)
leaderBoardDB.observe( .value, with: { (snapshot) in
print("scores scores", snapshot)
if let dictionary = snapshot.value as? [String: Any] {
for playa in dictionary {
let player = Player()
print("plaaaaayyyyyaaaaa", playa)
print("plaaaaayyyyyaaaaa key", playa.key)
print("plaaaaayyyyyaaaaa.value", playa.value)
player.id = playa.key
print(playa.key["name"])
}
}
}, withCancel: nil)
}
我得到以下结果:
plaaaaayyyyyaaaaa("inovoID",{ 名字= Tatiana; 点= 6; })plaaaaayyyyyaaaaa键inovoID plaaaaayyyyyaaaaa.value { 名字= Tatiana; 点= 6; } aaaa i id Optional("inovoID")
plaaaaayyyyyaaaaa ("inovoID", { name = Tatiana; points = 6; }) plaaaaayyyyyaaaaa key inovoID plaaaaayyyyyaaaaa.value { name = Tatiana; points = 6; } aaaa i id Optional("inovoID")
问题是我无法获得用户的姓名和积分.当我尝试使用:
the problem is that i can't obtain the name and the points of the user. when i try it with:
print(playa.key["name"])
它给了我这个错误:
不能用索引类型为"String"的下标为"String"类型的值
Cannot subscript a value of type 'String' with an index of type 'String'
有人可以帮我吗?
推荐答案
因为您的JSON是
"inovoID" : { "name" : "Tatiana", "points" : 6 }
-
playa.key
是"inovoID"
-
playa.value
是{ "name" : "Tatiana", "points" : 6 }
playa.key
is"inovoID"
playa.value
is{ "name" : "Tatiana", "points" : 6 }
键为String
,无法下标.这就是错误的意思.
The key is String
and cannot be subscripted. That's what the error says.
您需要订阅值并安全地强制转换类型以帮助编译器.
You need to subscribe the value and safely cast the type to help the compiler.
if let person = playa.value as? [String:Any] {
print(person["name"] as! String)
}
这篇关于如何在Swift 3中从字典中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!