如何在Swift 3中从字典中检索值 [英] How to retrieve a value from dictionary in Swift 3

查看:155
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆