ExSwift
ExSwift copied to clipboard
Using built-in contains function.
Would it be possible to use the built-in contains function as the basis for the contains method extensions? I've tried it out myself but it seems limited by the fact that the built-in contains function expects values to be Equatable while the generic Array, etc. can make no such guarantees.
Perhaps you have more insight?
Some of the ways I can think of are:
- Cast the array to an array of
Equatableobjects:
func contains <R: Equatable> (element: R) -> Bool {
return Swift.contains(unsafeBitCast(self, [R].self), element)
}
- Make a sequence of
Equatableto prevent an exception in case of nonEquatableobjects in the array:
func contains <R: Equatable> (element: R) -> Bool {
let seq = SequenceOf<R> { () -> GeneratorOf<R> in
var next = 0
return GeneratorOf<R> {
var item: R? = nil
while item == nil && next < self.count {
item = self[next++] as? R
}
return item
}
}
return Swift.contains(seq, element)
}
The first implementation has the downside of being unreliable, the second one looks too complex.