Skip to content

Instantly share code, notes, and snippets.

@niw
Last active June 23, 2022 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niw/35bebabdb68ff5ff2d2fc553688bd245 to your computer and use it in GitHub Desktop.
Save niw/35bebabdb68ff5ff2d2fc553688bd245 to your computer and use it in GitHub Desktop.
Wrapped property’s `didSet` is not really useful
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