[英]Swift's equatable protocol conformance check
我試圖用以下函數擴展Swift的Array
類:
func containsObjectIdenticalTo(obj: T) -> Bool {
// objectPassingTest returns the first object passing the test
return objectPassingTest { x in x == obj }
}
顯然,這不會編譯,因為編譯器還不知道是否為類型T
實現了==
。 然后我將代碼更改為此
func containsObjectIdenticalTo(obj: T) -> Bool {
return objectPassingTest {
x in
assert(x is Equatable && obj is Equatable)
return (x as Equatable) == (obj as Equatable)
} != nil
}
哪個也不起作用,因為無法檢查對Equatable
一致性(因為Equatable
沒有用@obj
定義) !
有什么想法嗎? 如果有一種方法可以直接斷言如果T
符合Equatable
,那會Equatable
,但我還沒有讀到任何地方。 在這些東西中,Swift似乎沒有Obj-C那么動態。
更新:嘗試了這個建議,它不起作用(不知道究竟是什么<T: Equatable>
是為了,它編譯)。
func containsObjectIdenticalTo<T: Equatable>(obj: T) -> Bool {
var x = self[0]
var y = self[0]
return x == y // Error here
}
指定T必須在Method的簽名中相等:
func containsObjectIdenticalTo<T: Equatable>(obj: T) -> Bool {/*...*/}
我從ExSwift得到了這個: https : //github.com/pNre/ExSwift
func contains <T: Equatable> (items: T...) -> Bool {
return items.all { self.indexOf($0) >= 0 }
}
func indexOf <U: Equatable> (item: U) -> Int? {
if item is Element {
if let found = find(reinterpretCast(self) as Array<U>, item) {
return found
}
return nil
}
return nil
}
func all (call: (Element) -> Bool) -> Bool {
for item in self {
if !call(item) {
return false
}
}
return true
}
也許你可以嘗試一下
怎么樣:
func containsObjectIdenticalTo<T : Equatable>(obj: T) -> Bool {
... etc ...
}
最后,我使用了這個解決方案
func containsObjectIdenticalTo<U: Equatable>(obj: U) -> Bool {
return objectPassingTest({
x in
return x as U == obj
}) != nil
}
可能不是最好的(即最安全的 )。 但它很棒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.