Created
June 26, 2025 13:45
-
-
Save ole/eee9fd551a79ede82cbe6e21f0f5ea11 to your computer and use it in GitHub Desktop.
Observable is both a macro and a protocol
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 Observation | |
protocol P: AnyObject, Observable { | |
var value: Int { get set } | |
} | |
@Observable | |
class MyObject: P { | |
var value: Int = 0 | |
} | |
// Usage: somewhere else in your code: | |
let obj: any P = MyObject() | |
withObservationTracking { | |
// Observe | |
print("willSet, value is", obj.value) | |
} onChange: { | |
print("onChange") | |
} | |
obj.value += 1 | |
// Prints: | |
// willSet, value is 0 | |
// onChange |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment