2017-06-19 48 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()