Skip to content

Instantly share code, notes, and snippets.

@DimaRU
Created July 5, 2018 18:33
Show Gist options
  • Save DimaRU/dc40a4b35528d332726ab9e96d763981 to your computer and use it in GitHub Desktop.
Save DimaRU/dc40a4b35528d332726ab9e96d763981 to your computer and use it in GitHub Desktop.
Swift keyPath playground
import Cocoa
class AppData {
var iDict1: [Int:Int] = [1:1, 2:2]
var iDict2: [Int:Int] = [1:11, 2:22]
var sDict1: [Int:String] = [1: "One", 2: "Two"]
var sDict2: [Int:String] = [1: "One2", 2: "Two2"]
static let propPath: [String: PartialKeyPath<AppData>] = [
"iDict1": \AppData.iDict1,
"iDict2": \AppData.iDict2,
"sDict1": \AppData.sDict1,
"sDict2": \AppData.sDict2
]
func printAll() {
for (key, path) in AppData.propPath {
print(key, type(of: path).rootType, type(of: path).valueType)
switch type(of: path).valueType {
case is Dictionary<Int, Int>.Type:
let iPath = path as! KeyPath<AppData, Dictionary<Int,Int>>
self[keyPath: iPath].forEach{ print("\($0):\($1)") }
case is Dictionary<Int, String>.Type:
let iPath = path as! KeyPath<AppData, Dictionary<Int,String>>
self[keyPath: iPath].forEach{ print("\($0):\($1)") }
default:
fatalError()
}
}
}
func modDict(dictName: String) {
guard let path = AppData.propPath[dictName] else {
return
}
switch type(of: path).valueType {
case is Dictionary<Int, Int>.Type:
let iPath = path as! ReferenceWritableKeyPath<AppData, Dictionary<Int,Int>>
self[keyPath: iPath].keys.forEach{ self[keyPath: iPath][$0]? += 1000 }
case is Dictionary<Int, String>.Type:
let sPath = path as! ReferenceWritableKeyPath<AppData, Dictionary<Int,String>>
self[keyPath: sPath].keys.forEach{ self[keyPath: sPath][$0]?.append("-----") }
default:
fatalError()
}
}
}
var appData = AppData()
print("Before:")
appData.printAll()
appData.modDict(dictName: "sDict1")
appData.modDict(dictName: "iDict2")
print("After:")
appData.printAll()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment