Cannot convert Binding<Type> to Binding<Protocol>是特定的错误消息,但潜在的问题是:什么是保存引用、然后从底层对象进行变异和读取的好架构?
示例:
。
下面是我尝试过的一个具体例子:这个应用程序有几个Animal,您可以使用这个应用程序来编辑currentAnimal的name。
错误 Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'
protocol Animal {
var name: String { get set }
}
struct Cow: Animal {
var name: String
}
struct Dog: Animal {
var name: String
}
class Model: ObservableObject {
@Published var dog: Dog = Dog(name: "dog 1")
// ** THIS IS THE IMPORTANT PART ** //
@Published var currentAnimal: Binding<Animal> = .constant(Cow(name: "cow 1"))
}
struct ContentView: View {
@StateObject var model = Model()
var body: some View {
VStack {
Text(model.dog.name) // Show the underlying Dog
}
.onAppear {
model.currentAnimal = $model.dog // Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'
}
.onTapGesture {
model.currentAnimal.wrappedValue.name = "dog 2" // Mutate state here
}
}
}是的,我知道https://developer.apple.com/forums/thread/652064,但我不认为做一个强制as!的案子是个好主意。有什么方法可以用泛型代替协议来解决这个问题吗?或者是类继承而不是协议?还是其他建筑?
发布于 2022-02-12 09:18:58
编辑:它与类一起工作:
protocol Animal {
var name: String { get set }
}
class Cow: Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Model: ObservableObject {
@Published var dog: Dog = Dog(name: "dog 1")
// ** THIS IS THE IMPORTANT PART ** //
@Published var currentAnimal: Animal = Cow(name: "cow 1")
}
struct ContentView: View {
@StateObject var model = Model()
var body: some View {
VStack {
Text(model.dog.name) // Show the underlying Dog
}
.onAppear {
model.currentAnimal = model.dog // Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'
}
.onTapGesture {
model.currentAnimal.name = "dog 2" // Mutate state here
}
}
}https://stackoverflow.com/questions/71088718
复制相似问题