Last active
June 10, 2019 21:20
-
-
Save calebkleveter/8034c2b934fac3e2784f293d1c113442 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Mirrorible { | |
var mirror: Mirror { get } | |
} | |
extension Mirrorible { | |
subscript (descendant key: String) -> Any { | |
return self.mirror.descendant(key) as Any | |
} | |
} | |
final class Reflector<T> where T: Mirrorible { | |
private var propertyNameCache: [PartialKeyPath<T>: String] | |
private var keyPathCache: [String: PartialKeyPath<T>] | |
private var mirror: Mirror | |
var value: T | |
var keyPaths: [String: PartialKeyPath<T>] { | |
return self.keyPathCache | |
} | |
var propertyNames: [PartialKeyPath<T>: String] { | |
return self.propertyNameCache | |
} | |
init(_ value: T) { | |
self.value = value | |
self.mirror = Mirror(reflecting: value) | |
self.propertyNameCache = [:] | |
self.keyPathCache = [:] | |
self.loadCache() | |
} | |
private func loadCache() { | |
self.mirror.children.forEach { child in | |
if let name = child.label { | |
let keyPath = \T.[descendant: name] as PartialKeyPath | |
self.propertyNameCache[keyPath] = name | |
self.keyPathCache[name] = keyPath | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment