Skip to content
This repository has been archived by the owner on Mar 29, 2018. It is now read-only.

Using built-in contains function. #87

Open
mklbtz opened this issue Mar 10, 2015 · 1 comment
Open

Using built-in contains function. #87

mklbtz opened this issue Mar 10, 2015 · 1 comment

Comments

@mklbtz
Copy link

mklbtz commented Mar 10, 2015

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?

@pNre
Copy link
Owner

pNre commented Mar 11, 2015

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants