Skip to content

Instantly share code, notes, and snippets.

@623637646
Last active May 7, 2024 08:29
Show Gist options
  • 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?
// Refer to https://stackoverflow.com/a/41543070/9315497
// https://talk.objc.io/episodes/S01E31-mutating-untyped-dictionaries
extension Dictionary {
subscript(jsonDict key: Key) -> [String: Any]? {
get {
return self[key] as? [String: Any]
}
set {
self[key] = newValue as? Value
}
}
subscript(jsonArray 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment