简体   繁体   English

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

[英]Swift protocol with associatedtype error

I create a function class : Bar , Bar use delegate that belong it to specific do something and this delegate comply with protocol FooDelegate , something like that: 我创建了一个函数类: 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!
}

but in class Bar : var delegate:FooDelegate! 但在类Bar: var delegate:FooDelegate! I got an error: 我收到一个错误:

Protocol 'FooDelegate' can only be used as a generic constraint because it has Self or associated type requirements 协议'FooDelegate'只能用作通用约束,因为它具有Self或相关类型要求

How could I fix this? 我怎么能解决这个问题?

You have a couple of options. 你有几个选择。

Firstly you can use a specific type of FooDelegate , like SomeFoo : 首先,您可以使用特定类型的FooDelegate ,例如SomeFoo

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

Or you can make Bar generic and define what type of Item the delegate needs: 或者您可以使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!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM