Skip to content

Instantly share code, notes, and snippets.

@623637646
Created March 8, 2024 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 623637646/6cb3ebecd926d293b578b3bce9148edb to your computer and use it in GitHub Desktop.
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?
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