user3925713
user3925713

Reputation: 569

Check array of optionals for nil

I have a number of optionals and would like to efficiently check to see if any of them is nil.

Ideally...

if contains([optional1, optional2, optional3], nil) { /* foo */ }

But swift won't let me do this. (Type 'S.Generator.Element -> L' does not conform to protocol 'NilLiteralConvertible')

And optionals can't be AnyObjects so I can't cast it to an NSArray either (to use .containsObject).

I could just write a for loop but that seems like bad style. Any suggestions?

Upvotes: 2

Views: 379

Answers (1)

Martin R
Martin R

Reputation: 540105

There are two contains() functions:

func contains<S : SequenceType where S.Generator.Element : Equatable>(seq: S, x: S.Generator.Element) -> Bool
func contains<S : SequenceType, L : BooleanType>(seq: S, predicate: @noescape (S.Generator.Element) -> L) -> Bool

The first one takes an element as the second argument, but requires that the elements conform to the Equatable protocol, which is not the case for optionals.

The second one takes a predicate as second argument, and that can be used here:

let optArray : [Int?] = [1, nil, 2]
if contains(optArray, { $0 == nil } ) {

}

But any solution must traverse the array until a nil element is found, so the above solution may be better readable but is not necessarily more efficient than a for-loop.

Upvotes: 4

Related Questions