Skip to content

Instantly share code, notes, and snippets.

@ctreffs
Created November 8, 2021 20:18
Show Gist options
  • Save ctreffs/c9efba8a93f33c71459478dc09f9b65b to your computer and use it in GitHub Desktop.
Save ctreffs/c9efba8a93f33c71459478dc09f9b65b to your computer and use it in GitHub Desktop.
KeyPathReflectable
// <https://github.com/tensorflow/swift-apis/blob/main/Sources/TensorFlow/Core/KeyPathIterable.swift>
// <https://github.com/apple/swift/blob/main/stdlib/public/core/ReflectionMirror.swift>
// <https://github.com/tensorflow/swift/blob/main/docs/DynamicPropertyIteration.md>
// <https://forums.swift.org/t/getting-keypaths-to-members-automatically-using-mirror/21207>
// <https://github.com/Azoy/Echo>
public protocol KeyPathReflectable {
func reflect(allKeyPaths keyPaths: inout [PartialKeyPath<Self>])
func reflect(allKeyPaths keyPaths: inout [String: PartialKeyPath<Self>])
}
extension KeyPathReflectable {
@inlinable
subscript(mirrorDescendant key: String) -> Any { Mirror(reflecting: self).descendant(key)! }
public func reflect(allKeyPaths keyPaths: inout [PartialKeyPath<Self>]) {
let mirror = Mirror(reflecting: self)
for case let (label?, _) in mirror.children {
keyPaths.append(\Self.[mirrorDescendant: label] as PartialKeyPath<Self>)
}
}
public func reflect(allKeyPaths keyPaths: inout [String: PartialKeyPath<Self>]) {
let mirror = Mirror(reflecting: self)
for case let (label?, _) in mirror.children {
keyPaths[label] = \Self.[mirrorDescendant: label] as PartialKeyPath<Self>
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment