I have an array of nullable items which may or may not have any nil
s in it:
let source = [1, 2, 3] as [Int?]
// or
let source = [1, 2, nil] as [Int?]
I want to turn it into an [Int]?
with the values as Int
s if no items are nil
or nil
if any item is nil
.
What's the idiomatic way to do 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!})
}
// This works, but seems likey to be non-idiomatic (as well as being ineffecient).
let result = toNonNullable(source)