我有此功能可以从FireBase
获取用户并在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",{ name = Tatiana; points = 6; })plaaaaayyyyyaaaaa key inovoID plaaaaayyyyyaaaaa.value { name = Tatiana; points = 6; } aaaa i id可选(" inovoID")
问题是我无法获得用户的名称和要点。当我试着用它时:
print(playa.key["name"])
它给了我这个错误:
无法下标类型'字符串'索引类型为' String'
有人可以帮帮我吗?
答案 0 :(得分:5)
因为你的JSON是
"inovoID" : { "name" : "Tatiana", "points" : 6 }
playa.key
是"inovoID"
playa.value
是{ "name" : "Tatiana", "points" : 6 }
密钥为String
,无法下标。这就是错误所说的。
您需要订阅值并安全地转换类型以帮助编译器。
if let person = playa.value as? [String:Any] {
print(person["name"] as! String)
}
答案 1 :(得分:3)
我认为您正在寻找:
findnum(N, N, M).
findnum(N, M, Res) :- N1 is N+1, N1 < M, findnum(N1, M, Res), Res is N1 + M.
您不需要遍历字典来访问它的值。如果您正在寻找密钥的价值,那就搞定吧。