swift - How do I turn an array of nullable items into a nullable array based on whether any of the items are null? -
i have array of nullable items may or may not have nils in it:
let source = [1, 2, 3] [int?] // or let source = [1, 2, nil] [int?] i want turn [int]? values ints if no items nil or nil if item nil.
what's idiomatic way this?
things i've tried:
// fails with: fatal error: can't unsafebitcast between types of different sizes let result = source as? [int] and:
func tononnullable<t>(array: [t?]) -> [t]? { if array.filter({$0 == nil}).count != 0 { return nil; } return array.map({$0!}) } // works, seems likey non-idiomatic (as being ineffecient). let result = tononnullable(source)
here's how write it:
let source = [1, 2, nil] [int?] var result : [int]? = { in source { if == nil { return nil } } return source.map {$0!} }() but doesn't meet "inefficient" consideration. has through array see if contains nil, nothing lost looping , doing that; inefficiency loop twice, because map loop. if hate that, here's way out:
var result : [int]? = { var temp = [int]() in source { if let = { temp.append(i) } else { return nil } } return temp }() lots of idiomatic swifties in formulations, think!