Skip to content

Instantly share code, notes, and snippets.

@calebkleveter
Last active June 10, 2019 21:20
Show Gist options
  • Save calebkleveter/8034c2b934fac3e2784f293d1c113442 to your computer and use it in GitHub Desktop.
Save calebkleveter/8034c2b934fac3e2784f293d1c113442 to your computer and use it in GitHub Desktop.
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