Skip to content

Instantly share code, notes, and snippets.

@AntiMoron
Created February 27, 2017 03:17
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 AntiMoron/e546bcacd94eaff74da20f61950876e0 to your computer and use it in GitHub Desktop.
Save AntiMoron/e546bcacd94eaff74da20f61950876e0 to your computer and use it in GitHub Desktop.
swift3 set value for keypath
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
fileprivate func _setDictionary( dict:inout [String: Any], value: Any, forKeys: ArraySlice<String>) {
guard forKeys.count > 1 else {
dict[forKeys.first!] = value
return
}
if var subdict = dict[forKeys.first!] as? [String: Any] {
print("lala")
_setDictionary(dict: &subdict, value: value, forKeys: forKeys[1..<forKeys.count])
dict[forKeys.first!] = subdict
}
}
func setDictionary( dict:inout [String: Any], value: Any, forKey: String) {
let keypaths = forKey.components(separatedBy: ".")
_setDictionary(dict: &dict, value: value, forKeys: keypaths[0..<keypaths.count])
}
var tester = ["hahah": [
"id":"123213",
"fuck": "tsetest"
]] as [String: Any]
setDictionary(dict: &tester, value: "444", forKey: "hahah.id")
print(tester)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment