具有关联类型错误的Swift协议

时间:2018-03-30 06:41:49

标签: swift generics swift-protocols

我创建了一个函数类: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!
}

但在课程栏中:var delegate:FooDelegate!我收到了错误:

  

协议' FooDelegate'只能用作通用约束   因为它有自我或相关的类型要求

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

你有几个选择。

首先,您可以使用特定类型的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!
}
相关问题