Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active September 10, 2024 11:59
Show Gist options
  • Save IanKeen/91ff0e6036fcfdf467c8bb9562fcf061 to your computer and use it in GitHub Desktop.
Save IanKeen/91ff0e6036fcfdf467c8bb9562fcf061 to your computer and use it in GitHub Desktop.
Partial<T>
/// A wrapper for a partial representation of a `T`.
/// It can be constructed over time, then later used to
/// build a complete `T`
@dynamicMemberLookup
public struct Partial<T> {
enum Error: Swift.Error {
case invalid(PartialKeyPath<T>)
}
// MARK: - Private Properties
private var data: [PartialKeyPath<T>: Any] = [:]
// MARK: - Lifecycle
public init() { }
public subscript<U>(dynamicMember keyPath: KeyPath<T, U>) -> U? {
get { return data[keyPath] as? U }
set { data[keyPath] = newValue }
}
public func contains(_ keyPath: PartialKeyPath<T>) -> Bool {
return data[keyPath] != nil
}
public mutating func combine(with other: Partial<T>) -> Partial<T> {
for (key, value) in other.data {
data[key] = value
}
return self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment