Skip to content

Instantly share code, notes, and snippets.

@ole
Created June 26, 2025 13:45
Show Gist options
  • Save ole/eee9fd551a79ede82cbe6e21f0f5ea11 to your computer and use it in GitHub Desktop.
Save ole/eee9fd551a79ede82cbe6e21f0f5ea11 to your computer and use it in GitHub Desktop.
Observable is both a macro and a protocol
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