Created
November 8, 2021 20:18
-
-
Save ctreffs/c9efba8a93f33c71459478dc09f9b65b to your computer and use it in GitHub Desktop.
KeyPathReflectable
This file contains hidden or 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
// <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