Middle+
How to make a class observable starting from iOS 17?
sobes.tech AI
Answer from AI
Starting from iOS 17, to make a class observable, you can use the new Observable protocol from Swift Concurrency. Instead of the familiar ObservableObject with @Published, now the class should conform to the Observable protocol and use an asynchronous change stream.
Example:
import SwiftUI
import Observation
@Observable
class MyModel {
var value: Int = 0
}
// Usage in SwiftUI
struct ContentView: View {
@StateObject private var model = MyModel()
var body: some View {
Text("Value: \(model.value)")
}
}
The key here is the @Observable annotation before the class, which automatically generates the necessary logic for change tracking. This simplifies the creation of observable models and their integration with SwiftUI.