How to write any (s: SequenceType) in Swift

Swift does not seem to have functions for any () or all (), so I'm trying to make my own. The closest I got is

func any<S: SequenceType where S.Generator.Element: BooleanType> (sequence: S) -> Bool{ var __g = sequence.generate() var first_element = __g.next() if first_element == nil{ return false } return reduce(sequence, first_element!, {$0 || $1}) } 

Change According to the comments, this function should look like this:

 func any<S: SequenceType where S.Generator.Element: BooleanType> (sequence: S) -> Bool{ return reduce(sequence, false, {$0 || $1}) } 

The compiler tells me

 'S.Generator.Element' is not convertible to 'Bool' 

I think I'm directly telling the compiler that it is on the second line. What am I missing?

+7
swift
source share
1 answer

Your problem is that next returns an optional parameter. This means that the reduction is awaiting the return of an optional value and $0 is optional. You will have to expand the option to be able to use the || operator . You also do not know what type is Bool , namely BooleanType . You should also convert it to the actual Bool by calling boolValue on it:

 func any<S: SequenceType where S.Generator.Element: BooleanType> (sequence: S) -> Bool{ var __g = sequence.generate() var first_element = __g.next() if first_element == nil{ return false } return reduce(sequence, first_element!.boolValue, {$0 || $1}) } 

However, in this case, I believe that simplicity is best:

 func any<S: SequenceType where S.Generator.Element: BooleanType> (sequence: S) -> Bool{ for element in sequence { if element.boolValue { return true } } return false } 

This is really more efficient because it returns as soon as it finds the first true , and does not always go through all this.

+3
source share

All Articles