Skip to content

Instantly share code, notes, and snippets.

@simonbs
Created November 4, 2023 19:09
Show Gist options
  • Save simonbs/4e92aaed85a93a35261ccc5db0cadc12 to your computer and use it in GitHub Desktop.
Save simonbs/4e92aaed85a93a35261ccc5db0cadc12 to your computer and use it in GitHub Desktop.
Property wrapper for proxying values.
@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
}
}
@wanbok-toss
Copy link

@simonbs
Hello, I have a question.
What are the benefits of using macros instead of @propertyWrapper?
Would it help reduce the binary size?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment