Search code examples
iosswiftswiftuiproperty-wrapper

Optional @ObservableObject in SwiftUI


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
}

Solution

  • 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")
           }
        }    
    }