ios - 解析我的 SWIFT 字典

标签 ios json swift dictionary firebase

我正在查询僵尸的 JSON 数据库,它以字典的形式返回它们。我不知道如何用 SWIFT 3 改变它

这是查询::

func getZombieAttackGroupFromDatabase () {
        ref?.child("Attacker Group").child((self.userParty?.leadID)!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get data
            print("PULLING DATA")
            if let value = snapshot.value as? NSDictionary{

                // break data into an Array of Zombie Structs

          //      print(value)

                for zombieID in value.allKeys {
                    print(value[zombieID])

                    let thisZombieID = zombieID
                    let thisZombieGroup = value[zombieID]["Group"]
                }



            } else {

            }
            // ...
        }) { (error) in
            print(error.localizedDescription)
        }


}

这部分:让 thisZombieGroup = value[zombieID]["Group"] 不被识别。我如何访问组?如果我明白了,我可以修改其他组件。

这是返回:

{
    "-KrNSmv64Ia32g5nw1L9" =     {
        Group = 15;
        Health = 250;
        "Is Undead" = true;
        Location = 1;
        Number = 0;
    };
    "-KrNSmv64Ia32g5nw1LA" =     {
        Group = 11;
        Health = 250;
        "Is Undead" = true;
        Location = 5;
        Number = 1;
    };
    "-KrNSmv64Ia32g5nw1LB" =     {
        Group = 2;
        Health = 250;
        "Is Undead" = true;
        Location = 3;
        Number = 2;
    };
    "-KrNSmv776r9eO6t7CY0" =     {
        Group = 14;
        Health = 250;
        "Is Undead" = true;
        Location = 0;
        Number = 3;
    };
    "-KrNSmv776r9eO6t7CY1" =     {
        Group = 0;
        Health = 250;
        "Is Undead" = true;
        Location = 4;
        Number = 4;
    };
}

如您所见,每个 Structs 都有一个父级,它是一个自动生成的 ID。我不知道如何访问它。

如何访问项目 1 中的每个元素?我需要父自动键“-KrNSmv64Ia32g5nw1L9”和每个子值。

"-KrNSmv64Ia32g5nw1L9" =     {
        Group = 15;
        Health = 250;
        "Is Undead" = true;
        Location = 1;
        Number = 0; 

最佳答案

value 转换为正确的 Swift 字典,而不是 NSDictionary

如果让 value = snapshot.value as? [字符串:任意]

您只需遍历字典的键,使用键值获取嵌入式字典,然后解析“僵尸数据”。

for key in value.keys {
    if let zombieData = value[key] as? [String:Any] {
        zombieData
        if let group = zombieData["Group"] as? Int, let health = zombieData["Health"] as? Int, let isUndead = zombieData["Is Undead"] as? Bool, let location = zombieData["Location"] as? Int, let number = zombieData["Number"] as? Int {
            //use the parsed data
        }
    }
}

关于ios - 解析我的 SWIFT 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45655323/

相关文章:

ios - Swift:Xcode tableView 无限滚动

swift - 强制解包可选导致过滤器崩溃

ios - 初始填充 UIImagePickerController 的图像

ios - 带有 UIView 的 SwiftUI 按钮

ios - Google Cloud Messaging Bitcode,链接器命令失败

json - 检索嵌套 Json 数组的第一条记录

javascript - 获取选定的 JSON 数据

ios - 推送到 viewController,同时以编程方式保留对先前 viewController 上的信息的访问

json - JSON 字符串中是否允许换行?

ios - 有没有办法在 Swift 中为 ErrorType 值指定错误代码?