我有一个协议(无法更改!即使通过例外)
protocol CalorieCountProtocol {
var calories: Int { get }
func description() -> String
}
我正在尝试实现这样的枚举:
enum SomeEnum: CalorieCountProtocol {
case calories(Int)
func description() -> String {
switch self {
case .calories(10):
return "wtf where elon musk its just 10 calories"
default:
return "yeeeeah its elon musk"
}
}
}
let someEnumTest: SomeEnum = SomeEnum.calories(10)
但我收到错误:
Type 'SomeEnum' does not conform to protocol 'CalorieCountProtocol'
Xcode 建议将卡路里作为变量添加到枚举中,但我不能在枚举中这样做?
一切都是正确的错误。
您的协议
CalorieCountProtocol
需要属性calories
和方法description()
,但您的枚举SomeEnum
没有属性calories
。不能改变吗?
好吧,但是你能扩展一下吗?让我们
CalorieCountProtocol
使用计算属性和关联值对枚举进行操作:结论:
但在
enum SomeEnum: CalorieCountProtocol {}
CalorieCountProtocol中,否则会出现“冗余一致性”错误,因为在扩展中为枚举添加协议的实现后,在枚举本身的定义中重新指定协议一致性就变得多余了。CalorieCountProtocol