使用@EnvironmentObject,我得到:“无法分配给属性:'viewModel'是仅获取属性”

时间:2020-03-07 20:13:37

标签: swift swiftui

我收到错误

无法分配给属性:“ viewModel”是仅获取属性 尝试使用泛型类型的@EnvironmentObject时。

import SwiftUI
import Combine

protocol HasCount {
    var count: Int { get set }
    var countPublished: Published<Int> { get set }
    var countPublisher: Published<Int>.Publisher { get set }
}

struct SomeView<ViewModelType: ObservableObject & HasCount>: View {
    @EnvironmentObject var viewModel: ViewModelType

    var body: some View {
        return VStack {
            Text("text")
            .onAppear {
                self.viewModel.count = 1
            }
        }
    }
}

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您的HasCount协议只限于以下对象

protocol HasCount: AnyObject { // << here !
    var count: Int { get set }
    var countPublished: Published<Int> { get set }
    var countPublisher: Published<Int>.Publisher { get set }
}