Last active
September 10, 2024 11:59
-
-
Save IanKeen/91ff0e6036fcfdf467c8bb9562fcf061 to your computer and use it in GitHub Desktop.
Partial<T>
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
/// 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