我有一个 associatedtype
的代码:
protocol ATState {
associatedtype Event
func nextState(event:Event) -> Self?
}
enum ATPlayerState:ATState {
case weak, powerful, poweringUp, poweringDown
func nextState(event: String) -> ATPlayerState? {
return nil
}
}
但是有一个编译时错误:“ATPlayerState does not conform to protocol ATState”;有一个修复程序可以添加 typealias Event = <Type>
,如果我添加:typealias Event = String
,它修复了错误。但我不明白为什么我需要这样做!
当我读到the documentation我看到了:
Thanks to Swift’s type inference, you don’t actually need to declare a concrete ItemType of Int as part of the definition of IntStack.
此外,示例不使用类型别名,它们只是实现方法。
那么这里不应该推断关联类型吗?
谢谢!
最佳答案
当您将事件添加为类型别名时,编译器不会报错?此代码块工作正常。
enum ATPlayerState:ATState {
case weak, powerful, poweringUp, poweringDown
typealias Event = String
internal func nextState(event: String) -> ATPlayerState? {
return .powerful
}
}
关于swift - 为什么 Swift 不能在这里推断类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202423/