SwiftUI中可选的@ObservableObject

dzjeubhm  于 2023-04-28  发布在  Swift
关注(0)|答案(2)|浏览(93)

我想在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
}
oalqel3c

oalqel3c1#

技术原因是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")
       }
    }    
}
gijlo24d

gijlo24d2#

实际上,您希望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
}

相关问题