Remove nested key from dictionary

前端 未结 5 1868
抹茶落季
抹茶落季 2020-12-20 16:07

Let\'s say I have a rather complex dictionary, like this one:

let dict: [String: Any] = [
    \"countries\": [
        \"japan\": [
            \"capital\":          


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 16:41

    When working with a subscript, if the subscript is get/set and the variable is mutable, then the entire expression is mutable. However, due to the type cast the expression "loses" the mutability. (It's not an l-value anymore).

    The shortest way to solve this is by creating a subscript that is get/set and does the conversion for you.

    extension Dictionary {
        subscript(jsonDict key: Key) -> [String:Any]? {
            get {
                return self[key] as? [String:Any]
            }
            set {
                self[key] = newValue as? Value
            }
        }
    }
    

    Now you can write the following:

    dict[jsonDict: "countries"]?[jsonDict: "japan"]?[jsonDict: "capital"]?["name"] = "berlin"
    

    We liked this question so much that we decided to make a (public) Swift Talk episode about it: mutating untyped dictionaries

提交回复
热议问题