2017-06-19 50 views
0

我試圖創建簡單的協議:斯威夫特協議屬性設置<Self>

protocol Groupable 
{ 
    var parent: Self? { get } 
    var children: Set<Self> { get } 
} 

children財產不能編譯,因爲:Type 'Self' does not conform to protocol 'Hashable'

有沒有什麼辦法,以確保SelfHashable?或者使用associatedtype任何其他的辦法解決這個,例如?

回答

1

把約束協議的方式類似於如何指定協議一致性(他們畢竟同樣的事情)

protocol Groupable: Hashable 
{ 
    var parent: Self? { get } 
    var children: Set<Self> { get } 
} 
+1

哦......那是太容易了。我準備好了先進的快速協議課程。我想我現在應該回到幼兒園。 – tzaloga

1

您需要使用協議繼承:

一協議可以繼承一個或多個其他協議,並且可以在其繼承的需求之上添加更多的需求。協議繼承的語法類似於類繼承的語法,但可以選擇列出多個繼承協議,並用逗號分隔。

通過從Hashable繼承,您的類將需要符合此協議。 此外,在具體的例子,你需要讓你的類決賽。有關說明,請參閱A Swift protocol requirement that can only be satisfied by using a final class

下面是一個例子:

protocol Groupable: Hashable { 
    var parent: Self? { get } 
    var children: Set<Self> { get } 
} 


final class MyGroup: Groupable { 

    var parent: MyGroup? 
    var children = Set<MyGroup>() 

    init() { 

    } 

    var hashValue: Int { 
     return 0 
    } 
} 

func ==(lhs: MyGroup, rhs: MyGroup) -> Bool { 
    return true 
} 



let a = MyGroup()