爲函數find
是該接口/是:
func find<C : CollectionType where C.Generator.Element : Equatable>(domain: C,
value: C.Generator.Element) -> C.Index?
這表示的C
的CollectionType
必須是Equatable
,此外元件,該value
也必須是Equatable
。
[Note Swift 3.0:從Swift 3.0開始,您需要使用index
函數,它有兩種變體。在第一個,你會提供你自己的斷言:
func index(where: (Self.Generator.Element) -> Bool) -> Self.Index?
在第二,你的元素必須equatable:
// Where Generator.Element : Equatable
func index(of: Self.Generator.Element) -> Self.Index?
如果你決定去equatable
路線,那麼以下適用。 注完]
你Score
結構是不Equatable
,因此錯誤。 你需要弄清楚分數彼此相等意味着什麼。也許它是一些數字'分數';也許它是'分數'和'用戶ID'。這取決於你的Score
抽象。一旦你知道,你使用實現==
:
func == (lhs:Score, rhs:Score) -> Bool {
return // condition for what it means to be equal
}
注:如果您使用class
,因此得分有「身份」,那麼就可以實現這個爲:
func == (lhs:Score, rhs:Score) -> Bool { return lhs === rhs }
你用繩子例如工作,因爲String
是Equatable
。如果您在斯威夫特庫代碼看看你會看到:
extension String : Equatable {}
func ==(lhs: String, rhs: String) -> Bool
您已經找到原因。 'Score'必須實現'Equatable'協議(無論是結構還是類)。 –
可能與此處相同的問題:http://stackoverflow.com/questions/27887387/how-to-use-contains-with-two-arrays-of-objects –