使用从另一个协议继承的协议作为关联类型

时间:2019-03-04 05:52:58

标签: swift swift-protocols associated-types

我正在尝试制定一种具有两种关联类型的协议。这些关联类型之一是用于委托的。当我尝试使用另一个协议作为关联类型时,出现错误“类型'HostConnectionService'不符合协议'ConnectionService'”。我的代码如下:

protocol ConnectionService: class {
    associatedtype Peer: Sharelist.Peer
    associatedtype Delegate: ConnectionServiceDelegate
    var connectedPeers: [Peer] { get }
    var delegate: Delegate? { get }
}

protocol ConnectionServiceDelegate { }

// Error
class HostConnectionService: NSObject, ConnectionService {
    typealias Peer = GuestPeer
    typealias Delegate = HostConnectionServiceDelegate

    var delegate: HostConnectionServiceDelegate?
    var connectedPeers: [GuestPeer] = []
}

protocol HostConnectionServiceDelegate: ConnectionServiceDelegate { }

当我换行时

typealias Delegate = HostConnectionServiceDelegate

成为非协议类型,我不再收到错误:

struct NonProtocolConnectionServiceDelegate: ConnectionServiceDelegate { }

// No Error
class HostConnectionSertice: NSObject, ConnectionService {
    ...
    typealias Delegate = NonProtocolConnectionServiceDelegate
    ...
}

这是Swift的基本限制,还是我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的示例太复杂了,难以理解。我试图简化它。

它编译没有错误:

protocol ProtocolA {}

protocol ProtocolB {
    associatedtype SomeType
}

class SomeClass: ProtocolB {
    typealias SomeType = ProtocolA
}

let object = SomeClass()

但是下面的示例不再编译:

protocol ProtocolA {}

protocol ProtocolB {
    associatedtype SomeType: ProtocolA
}

class SomeClass: ProtocolB {
    typealias SomeType = ProtocolA
}

错误如下:

  

错误:类型'SomeClass'不符合协议'ProtocolB'

     

注意:可能的预期匹配“ SomeType”(又称“ ProtocolA”)不符合“ ProtocolA”

这是因为protocols don't conform to themselves

根据您的情况,很可能有必要制作类模板:

protocol ProtocolA {}

protocol ProtocolB {
    associatedtype SomeType: ProtocolA
}

class SomeClass<T: ProtocolA>: ProtocolB {
    typealias SomeType = T
}

extension Int: ProtocolA {}
extension Double: ProtocolA {}

let object1 = SomeClass<Int>()
let object2 = SomeClass<Double>()