簡體   English   中英

使用從另一個協議繼承的協議作為關聯類型

[英]Use protocol that inherits from another protocol as an associated type

我正在嘗試制作一個具有兩個關聯類型的協議。 這些關聯類型之一是用於委托的。 當我嘗試使用另一個協議作為關聯類型時,出現錯誤“類型'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的基本限制,還是我做錯了什么?

您的示例太復雜,難以理解。 我試圖簡化它。

它編譯沒有錯誤:

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'(aka'ProtocolA')不符合'ProtocolA'

這是因為協議不符合自己

在您的情況下,最有可能需要制作類模板:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM