Created
February 4, 2026 14:55
-
-
Save DanielCardonaRojas/f1a8fb330de578079e0971c4c67bb200 to your computer and use it in GitHub Desktop.
Patch models with dynamic member lookup
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 Patch<T> { | |
| private var patches: [PartialKeyPath<T>: Any] = [:] | |
| subscript<U>(dynamicMember keyPath: WritableKeyPath<T, U>) -> U? { | |
| get { patches[keyPath] as? U } | |
| set { patches[keyPath] = newValue } | |
| } | |
| var modifiedFields: Set<PartialKeyPath<T>> { | |
| Set(patches.keys) | |
| } | |
| func hasChanges(in keyPath: PartialKeyPath<T>) -> Bool { | |
| patches[keyPath] != nil | |
| } | |
| func apply(to instance: T) -> T { | |
| var result = instance | |
| for (keyPath, value) in patches { | |
| if let writableKeyPath = keyPath as? WritableKeyPath<T, Any> { | |
| result[keyPath: writableKeyPath] = value | |
| } | |
| } | |
| return result | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment