首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法将Binding<Type>转换为Binding<Protocol>

无法将Binding<Type>转换为Binding<Protocol>
EN

Stack Overflow用户
提问于 2022-02-12 03:20:57
回答 1查看 114关注 0票数 0

Cannot convert Binding<Type> to Binding<Protocol>是特定的错误消息,但潜在的问题是:什么是保存引用、然后从底层对象进行变异和读取的好架构?

示例:

  • 在RPG中,你的角色有一个currentArmor。你想要它受到伤害。
  • 在口袋妖怪,你跟踪一个currentPokemon。它需要升级。Instagram中的
  • ,您有一个selectedPost,您希望使用like按钮来改变底层的post。

下面是我尝试过的一个具体例子:这个应用程序有几个Animal,您可以使用这个应用程序来编辑currentAnimalname

错误 Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'

代码语言:javascript
复制
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!的案子是个好主意。有什么方法可以用泛型代替协议来解决这个问题吗?或者是类继承而不是协议?还是其他建筑?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-12 09:18:58

编辑:它与类一起工作:

代码语言:javascript
复制
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
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71088718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档