1
在Swift 2.1(運行XCode 7.2)中,我試圖讓協議的關聯類型符合Equatable。使Swift協議符合相關類型的Equatable
// (#1)
/**
A Node in a graph
*/
public protocol GraphNode : Equatable {
typealias Content : Equatable
/**
The content of the node.
E.g. in a graph of strings, this is a string
*/
var content: Content {get}
/// The list of neighbours of this Node in the graph
var children: [Self] {get}
}
我們可以有一個定義不同類型的相關類型協議的非均質實現,我希望我將無法在這裏定義(在協議層面,而不是在執行級)相等功能:
// (#2)
/// Won't compile, as expected
public func ==(lhs: GraphNode, rhs: GraphNode) {
return lhs.content == rhs.content
}
這是因爲我沒有保證lhs.Content
相同類型rhs.Content
。 不過,我希望我能有一些通用的約束指定,如:
// (#3)
/// Won't compile, why?
public func ==<Node1 : GraphNode, Node2 : GraphNode where Node1.Content == Node2.Content>(lhs: Node1, rhs: Node2)
{
return lhs.content == rhs.content // ERROR: Binary operator '==' cannot be applied to two 'Node1.Content' operands
}
在#3
,我們知道,無論LHS和RHS具有相同類型的,我們知道(從相關類型的規範如Equatable
)Content
是可以等化的。那爲什麼我不能比較它們呢?
謝謝,就是這樣!有時你只需要第二雙眼睛(或更好的彙編錯誤報告:)) – Marco83