Created
February 3, 2026 22:20
-
-
Save jayrhynas/88669ab736bfd6b3cd4e44e96c59da26 to your computer and use it in GitHub Desktop.
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
| @dynamicMemberLookup | |
| struct Partial<Wrapped> { | |
| private struct AnyProperty { | |
| let keyPath: PartialKeyPath<Wrapped> | |
| let value: Any | |
| let writer: (inout Wrapped, Any) -> Void | |
| init<T>(keyPath: WritableKeyPath<Wrapped, T>, value: Any) { | |
| self.keyPath = keyPath | |
| self.value = value | |
| self.writer = { instance, value in | |
| instance[keyPath: keyPath] = value as! T | |
| } | |
| } | |
| func update(_ wrapped: inout Wrapped) { | |
| self.writer(&wrapped, value) | |
| } | |
| } | |
| private var values: [PartialKeyPath<Wrapped>: AnyProperty] = [:] | |
| subscript<T: Codable>(dynamicMember keyPath: WritableKeyPath<Wrapped, T>) -> T? { | |
| get { self.values[keyPath]?.value as? T } | |
| set { | |
| if let value = newValue { | |
| self.values[keyPath] = AnyProperty(keyPath: keyPath, value: value) | |
| } else { | |
| self.values.removeValue(forKey: keyPath) | |
| } | |
| } | |
| } | |
| func apply(to original: Wrapped) -> Wrapped { | |
| var copy = original | |
| for (_, property) in values { | |
| property.update(©) | |
| } | |
| return copy | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment