gpt4 book ai didi

协议(protocol)中使用的 Swift 通用类型不起作用

转载 作者:行者123 更新时间:2023-11-28 15:37:26 25 4
gpt4 key购买 nike

我将我的麻烦简化为一个关于使用通用类型和协议(protocol)的小演示。这是代码。

protocol Food {

}

class Meat: Food {

}

class Cake: Food {

}

protocol EatProtocol {
func eat<T: Food>(_: T)
}

class Person: EatProtocol {
func eat<T>(_: T) where T : Food {
print("eat food")
}
}

class Man: Person {
override func eat<T>(_: T) where T : Meat {
print("eat meat")
}
}

class Woman: Person {
override func eat<T>(_: T) where T : Cake {
print("eat cake")
}
}

let man = Man()
let woman = Woman()
let manyPeople: [EatProtocol] = [man, woman]

let meat = Meat()
let cake = Cake()
let manyFood: [Food] = [meat, cake]

for (index, people) in manyPeople.enumerated() {
let food = manyFood[index]
people.eat(food)//error: Cannot invoke 'eat' with an argument list of type '(Food)'
}

问题是我确定在 for 循环中项目得到正确的食物,但编译器给我那个错误

最佳答案

这里有一个根本问题:并非所有的食客都能吃到所有种类的食物。在这个特定示例中,我能想到的最好方法是使用 switch 来枚举可能的组合、安全地转换并进行调用:

protocol Food {}
class Meat: Food {}
class Cake: Food {}

protocol Eater {
func eat<T: Food>(_: T)
}

class Person: Eater {
func eat<T>(_: T) where T: Food {
print("eat food")
}
}

class Man: Person {
override func eat<T>(_: T) where T: Meat {
print("eat meat")
}
}

class Woman: Person {
override func eat<T>(_: T) where T : Cake {
print("eat cake")
}
}

let eaters: [Eater] = [Man(), Woman()]
let foods: [Food] = [Cake(), Cake()]

for (food, eater) in zip(foods, eaters) {
switch (food, eater) {
case let (meat as Meat, man as Man): man.eat(meat)
case let (cake as Cake, woman as Woman): woman.eat(cake)
//...
default:
print("\(eater) (of type: \(type(of: eater))) cannot eat \(food) (of type: \(type(of: food)))")
continue
}
}

关于协议(protocol)中使用的 Swift 通用类型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44147982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com