6

我想在 SwiftUI 中有一个可选的@ObservedObject,但我不断收到编译时错误。

Property type 'AModel?' does not match that of the 'wrappedValue' property of its wrapper type 'ObservedObject'

这是一些最小的可重现代码。

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
}
4

2 回答 2

8

技术原因是它Optional不是一个类,所以它不能符合ObservableObject.

但是,如果您想避免重构对象本身 - 例如,如果它不在您的控制范围内 - 您可以执行以下操作:

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")
       }
    }    
}
于 2021-04-12T20:31:28.553 回答
2

您实际上希望您的init参数是optional,而不是 struct 属性。在你的情况下,我会简单地做:

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
}

于 2021-07-19T01:10:50.473 回答