2017-10-20 1 views
0

Ich bin ein bisschen stecken, versucht, einen Container für meine UI-Elemente zu definieren.Generics Struct Implementierungsprotokoll mit zugehörigem Typ

Als ich etwas, das eine nicht eindeutige Markierung, einen Wert, der sein kann jedes vergleichbare Objekt und ein Konzept des Seins die bevorzugte Option kam ich mit dem folgenden Protokoll verkapselt wollte:

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

Jetzt möchte ich Implementiere das Protokoll in einer generischen Struktur und ich kann nicht herausfinden, wie. Was ich tun möchte, ist

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

Aber der Compiler beschwert sich, dass Type 'Option<Key, Value>' does not conform to protocol 'OptionProtocol'

Jede mögliche Zeiger hilfreich

Antwort

1

Die Antwort ist ziemlich einfach war. Ich musste Schlüssel und Wert in der Struktur einschränken. Die folgende Struktur kompiliert wie erwartet

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