Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Created February 4, 2026 14:55
Show Gist options
  • Select an option

  • Save DanielCardonaRojas/f1a8fb330de578079e0971c4c67bb200 to your computer and use it in GitHub Desktop.

Select an option

Save DanielCardonaRojas/f1a8fb330de578079e0971c4c67bb200 to your computer and use it in GitHub Desktop.
Patch models with dynamic member lookup
@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