Skip to content

Instantly share code, notes, and snippets.

@Ridwy
Created January 8, 2016 03:26
Show Gist options
  • Save Ridwy/31ad7ce6f1abf6a94c75 to your computer and use it in GitHub Desktop.
Save Ridwy/31ad7ce6f1abf6a94c75 to your computer and use it in GitHub Desktop.
import Foundation
import SwiftyJSON
extension JSON {
func update(keyPath: String, value: JSON?) -> JSON {
let keys = keyPath.componentsSeparatedByString(".")
guard let targetKey = keys.first else {
return self
}
let targetValue: JSON?
if 1 < keys.count {
let subPath = keyPath.substringFromIndex(keyPath.startIndex.advancedBy(targetKey.characters.count + 1))
targetValue = self[targetKey].update(subPath, value: value)
} else {
targetValue = value
}
var result = JSON([:])
for (key, subJson) in self {
if key == targetKey {
if let targetValue = targetValue {
result[key] = targetValue
}
} else {
result[key] = subJson
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment