Last active
June 23, 2022 05:54
-
-
Save niw/35bebabdb68ff5ff2d2fc553688bd245 to your computer and use it in GitHub Desktop.
Wrapped property’s `didSet` is not really useful
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
import Foundation | |
@propertyWrapper | |
struct Wrapper<T> { | |
class Box<T> { | |
var value: T | |
init(_ initial: T) { | |
value = initial | |
} | |
} | |
var projectedValue: Box<T> | |
var wrappedValue: T { | |
get { | |
return projectedValue.value | |
} | |
nonmutating set { | |
projectedValue.value = newValue | |
} | |
} | |
init(wrappedValue: T) { | |
projectedValue = Box<T>(wrappedValue) | |
} | |
} | |
struct S { | |
@Wrapper | |
var a: Int = 1 { | |
didSet { | |
print("didSet") | |
} | |
} | |
} | |
let s = S() | |
print(s.a) // 1 | |
s.a = 2 // `didSet` is called. | |
print(s.a) // 2 | |
s.$a.value = 3 // We can bypass `didSet` by changing wrappedValue via projectedValue. | |
print(s.a) // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment