I want to have an optional @ObservedObject in SwiftUI but I keep getting a compile time error of.
Property type 'AModel?' does not match that of the 'wrappedValue' property of its wrapper type 'ObservedObject'
Here is some minimum reproducible code.
import SwiftUI
public struct AView: View {
//MARK: View Model
//Error thrown here.
@ObservedObject var model: AModel?
//MARK: Body
public var body: some View {
Text("\(model?.value ?? 0)")
}
//MARK: Init
public init() {
}
}
class AModel: ObservableObject {
let value: Int = 0
}
The technical reason is that Optional
is not a class, so it cannot be conformed to ObservableObject
.
But if you want to avoid refactoring the object itself - for example, if it's not in your control - you could do something like this:
struct AView: View {
private struct Content: View {
@ObservedObject var model: AModel
var body: some View {
Text("\(model.value)")
}
}
var model: AModel?
var body: some View {
if let model = model {
Content(model: model)
} else {
Text("0")
}
}
}
You actually want your init
argument to be optional, not the struct property.
In your case I would simply do:
import SwiftUI
public struct AView: View {
//MARK: View Model
@ObservedObject var model: AModel
//MARK: Body
public var body: some View {
Text("\(model.value)")
}
//MARK: Init
public init(model: AModel? = nil) {
self.model = model ?? AModel()
}
}
class AModel: ObservableObject {
let value: Int = 0
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With