簡體   English   中英

具有相關類型的泛型結構實現協議

[英]generics struct implementing protocol with associated type

嘗試為ui元素定義容器時,我有些困惑。

當我想要封裝非唯一標簽的東西,一個可以是任何可比較對象的值以及成為首選選項的概念時,我想到了以下協議:

protocol OptionProtocol:Comparable {
    associatedtype Key:Comparable
    associatedtype Value:Comparable

    var key:Key { get set }
    var value:Value { get set }
    var main:Bool { get set }

    static func <(lhs: Self, rhs: Self) -> Bool

    static func ==(lhs: Self, rhs: Self) -> Bool

}

extension OptionProtocol {
    static func <(lhs: Self, rhs: Self) -> Bool {
        let equalKeys = lhs.key == rhs.key
        return  equalKeys ? lhs.value < rhs.value : lhs.key < rhs.key
    }

    static func ==(lhs: Self, rhs: Self) -> Bool{
        return  (lhs.value == rhs.value) && (lhs.key == rhs.key)
    }
}

現在,我想以通用結構實現該協議,但我不知道該怎么做。 我想做的是

struct Option<Key, Value>: OptionProtocol  {
    var key:Key
    var value:Value
    var main:Bool
}

但是編譯器抱怨Type 'Option<Key, Value>' does not conform to protocol 'OptionProtocol'

任何指針都會有所幫助

答案很簡單。 我需要在結構中約束鍵和值。 以下結構按預期編譯

struct Option<Key, Value>:OptionProtocol where Key:Comparable, Value:Comparable {
    var key:Key
    var value:Value
    var main:Bool
}

暫無
暫無

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

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