swift - Check array of optionals for nil -
i have number of optionals , efficiently check see if of them nil.
ideally...
if contains([optional1, optional2, optional3], nil) { /* foo */ }
but swift won't let me this. (type 's.generator.element -> l' not conform protocol 'nilliteralconvertible')
and optionals can't anyobjects can't cast nsarray either (to use .containsobject).
i write loop seems bad style. suggestions?
there 2 contains()
functions:
func contains<s : sequencetype 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 1 takes element second argument, requires elements conform equatable
protocol, not case optionals.
the second 1 takes predicate second argument, , can used here:
let optarray : [int?] = [1, nil, 2] if contains(optarray, { $0 == nil } ) { }
but solution must traverse array until nil
element found, above solution may better readable not more efficient for-loop.
Comments
Post a Comment