如何从Swift 3中的字典中检索值

时间:2016-12-09 18:50:16

标签: swift dictionary

我有此功能可以从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'

有人可以帮帮我吗?

2 个答案:

答案 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.

您不需要遍历字典来访问它的值。如果您正在寻找密钥的价值,那就搞定吧。