【问题标题】:Swift protocol with associatedtype error带有关联类型错误的 Swift 协议
【发布时间】:2018-03-30 06:41:48
【问题描述】:

我创建了一个函数类:BarBar 使用属于它的委托做某事并且这个委托符合协议FooDelegate,类似这样:

protocol FooDelegate{
    associatedtype Item

    func invoke(_ item:Item)
}

class SomeFoo:FooDelegate{
    typealias Item = Int

    func invoke(_ item: Int) {
        //do something...
    }
}

class Bar{
    //In Bar instance runtime ,it will call delegate to do something...
    var delegate:FooDelegate!
}

但是在 Bar 类中:var delegate:FooDelegate! 我得到了一个错误:

Protocol 'FooDelegate' 只能用作通用约束 因为它有 Self 或关联的类型要求

我该如何解决这个问题?

【问题讨论】:

  • 您收到此错误是因为FooDelegate 具有关联类型item。不确定您的情况,但您可能想要类型擦除
  • 你是对的!我知道。但是你能谈谈类型擦除的细节吗,谢谢

标签: swift generics swift-protocols


【解决方案1】:

你有几个选择。

首先你可以使用特定类型的FooDelegate,比如SomeFoo

class Bar {
    //In Bar instance runtime ,it will call delegate to do something...
    var delegate: SomeFoo!
}

或者您可以将Bar 设为通用并定义委托需要的Item 类型:

class Bar<F> where F: FooDelegate, F.Item == Int {
    //In Bar instance runtime ,it will call delegate to do something...
    var delegate: F!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多