【问题标题】:Get child of dictionary with unknown parent key获取具有未知父键的字典的子级
【发布时间】:2019-08-20 18:22:46
【问题描述】:

我有一个类型为 [String: Any] 的字典,看起来像这样

"arExtensions" : {
        "images" : {
          "-LmgO2yG_TWbfOM4Y8X3" : {
            "imagePath" : "https://firebasestorage.googleapis.com/v0/b/gpk-citycards.appspot.com/o/ARResources%2F78E88F6D-52F0-43A3-B585-9760D19F0B81?alt=media&token=be3a664f-a94b-4ead-bea4-1197155c016e",
            "position" : "bottom"
          },
          "-LmgO4qaMKupHZIAEoLk" : {
            "imagePath" : "https://firebasestorage.googleapis.com/v0/b/gpk-citycards.appspot.com/o/ARResources%2FC7303CF9-0E86-4DC6-A5F5-2761537F0A30?alt=media&token=1f928774-8221-474b-881e-7f395e439131",
            "position" : "rightMiddle"
          },
          "-LmgO9vLT8rEx9Ndog4S" : {
            "imagePath" : "https://firebasestorage.googleapis.com/v0/b/gpk-citycards.appspot.com/o/ARResources%2F9132B5B6-E904-4BCE-B56A-0271CB901A7D?alt=media&token=bd66cd1d-494b-4a82-8d74-6e00ac8c8ae6",
            "position" : "leftMiddle"
          }
        }
      }

我想将图像添加到对象中。

var imageObjects: [ImageObject] = []

我知道我可以用这样的键获取值

let dictImages: [String: Any] = dictArExtensions["images"] as! [String : Any]

很遗憾,我不知道图像之子的钥匙。

通过两次迭代,第一次获得密钥,第二次获得所需的值我解决了这样的问题

        var imageKeys: [String] = []
        for dict in dictImages{
            print(dict.key)
            imageKeys.append(dict.key)
            print(dict.value)
        }

        for keys in imageKeys{
            let dictImage: [String: Any] = dictImages[keys] as! [String : Any]
            let imagePath = dictImage["imagePath"] as? String
            let position = dictImage["position"] as? String

            imageObjects.append(ImageObject(imagePath: imagePath!, position: position!))
        }

但是,这似乎是一个糟糕的解决方案。 有没有更好或更专业的解决方案?

【问题讨论】:

    标签: swift dictionary


    【解决方案1】:

    您可以使用keyvalue 非常简单地枚举字典,但key 实际上并未使用。

    如果您将子字典声明为[String:String],则可以摆脱类型转换

    for (_, value) in dictImages {
        let dictImage = value as! [String:String]
        let imagePath = dictImage["imagePath"]
        let position = dictImage["position"]
    
        imageObjects.append(ImageObject(imagePath: imagePath!, position: position!))
    }
    

    请阅读Language Guide中关于字典的部分

    【讨论】:

    • 谢谢,我会尽快尝试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多