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

Swift protocol with associatedtype error

我创建了一个函数 class : Bar, Bar 使用属于它的委托来做一些特定的事情并且这个委托遵守协议 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!
}

但在 class 栏中:var delegate:FooDelegate! 我得到一个错误:

Protocol 'FooDelegate' can only be used as a generic constraint because it has Self or associated type requirements

我该如何解决这个问题?

你有几个选择。

首先你可以使用特定类型的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!
}