Created
March 8, 2024 10:08
-
-
Save 623637646/6cb3ebecd926d293b578b3bce9148edb to your computer and use it in GitHub Desktop.
How to update a value in a nested dictionary given path fragment in Swift?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Dictionary { | |
subscript(jsonDict key: Key) -> [String:Any]? { | |
get { | |
return self[key] as? [String:Any] | |
} | |
set { | |
self[key] = newValue as? Value | |
} | |
} | |
} | |
var dict: [String: Any] = [ | |
"countries": [ | |
"japan": [ | |
"capital": [ | |
"name": "Tokyo", | |
], | |
] | |
], | |
"airports": "" | |
] | |
dict[jsonDict: "countries"]?[jsonDict: "japan"]?[jsonDict: "capital"]?["name"] = "Berlin" | |
let name = dict[jsonDict: "countries"]?[jsonDict: "japan"]?[jsonDict: "capital"]?["name"] | |
print(name) | |
// Refer to https://stackoverflow.com/a/41543070/9315497 | |
// https://talk.objc.io/episodes/S01E31-mutating-untyped-dictionaries |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment