swift - 为什么 Swift 不能在这里推断类型?

标签 swift

我有一个 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/

相关文章:

swift - 如何通过快速扩展重写 NSDictionary 中的描述属性?

ios - 如何使用 XCUITest 测试 UIImageView 是否包含具有特定名称的图像?

ios - 如何在 tableview 单元格中实现 iOS 图表?

iOS - IAP 问题,对应用商店收据感到困惑

ios - Swift 同时检测屏幕左右两侧的触摸

如果无法返回 Facebook 个人资料,Swift 2.3 会崩溃

Swift NSManagedObjects 不支持 mutableSetValueForKey

arrays - 如何获取 CGPoint 数组的每个值重复的次数

ios - 创建一个空的 var 给我一个错误

ios - 从 UITableViewCell 中的 UISwitch 更新核心数据