ExSwift icon indicating copy to clipboard operation
ExSwift copied to clipboard

Using built-in contains function.

Open mklbtz opened this issue 10 years ago • 1 comments

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?

mklbtz avatar Mar 10 '15 16:03 mklbtz

Some of the ways I can think of are:

  • Cast the array to an array of Equatable objects:
func contains <R: Equatable> (element: R) -> Bool {
    return Swift.contains(unsafeBitCast(self, [R].self), element)
}
  • Make a sequence of Equatable to prevent an exception in case of non Equatable objects 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.

pNre avatar Mar 11 '15 19:03 pNre