Created
November 4, 2023 19:09
-
-
Save simonbs/4e92aaed85a93a35261ccc5db0cadc12 to your computer and use it in GitHub Desktop.
Property wrapper for proxying values.
This file contains 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
@propertyWrapper | |
struct Proxy<EnclosingType, Value> { | |
typealias ValueKeyPath = ReferenceWritableKeyPath<EnclosingType, Value> | |
typealias SelfKeyPath = ReferenceWritableKeyPath<EnclosingType, Self> | |
static subscript( | |
_enclosingInstance instance: EnclosingType, | |
wrapped wrappedKeyPath: ValueKeyPath, | |
storage storageKeyPath: SelfKeyPath | |
) -> Value { | |
get { | |
let keyPath = instance[keyPath: storageKeyPath].keyPath | |
return instance[keyPath: keyPath] | |
} | |
set { | |
let keyPath = instance[keyPath: storageKeyPath].keyPath | |
instance[keyPath: keyPath] = newValue | |
} | |
} | |
@available(*, unavailable, message: "@Proxy can only be applied to classes") | |
var wrappedValue: Value { | |
get { fatalError() } | |
set { fatalError() } | |
} | |
private let keyPath: ValueKeyPath | |
init(_ keyPath: ValueKeyPath) { | |
self.keyPath = keyPath | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm replacing the property wrapper with the following macro.