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

Use protocol that inherits from another protocol as an associated type

我正在尝试创建一个具有两个关联类型的协议。这些关联类型之一用于委托。当我尝试使用另一个协议作为关联类型时,出现错误 "Type 'HostConnectionService' does not conform to protocol '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 限制,还是我做错了什么?

你的例子太复杂了,看不懂。我试图简化它。

编译无误:

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
}

错误如下:

error: type 'SomeClass' does not conform to protocol 'ProtocolB'

note: possibly intended match 'SomeType' (aka 'ProtocolA') does not conform to 'ProtocolA'

这是因为

您的情况很可能需要制作 class 模板:

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>()