如果@EnvironmentObject如何创建泛型?

I've recently come across the need to write a Mock of a Class, as it causes the SwiftUI preview from working. Unfortunately, I get the error:

Property type 'T' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'

在视图结构中:

struct ContentView<T>: View {
    @EnvironmentObject var mockFoobar: T
    ...
}

还有错误:

Type of expression is ambiguous without more context

对于预览结构:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let mockFoobar: MockFoobar = MockFoobar()
        return ContentView<MockFoobar>()
            .environmentObject(mockFoobar)
    }
}
评论
qodio
qodio

EnvironmentObject必须是ObservableObject,所以这里是修复方法

struct ContentView<T: ObservableObject>: View {
    @EnvironmentObject var mockFoobar: T

    // .. other code here
点赞
评论