let elements: [(Int?, Int?)] = [(1, 2), (2, 1), (3, nil), (nil, 3), (5, 6), (6, 5)]
let result = elements.filter { $0.0 != nil } as! [(Int, Int?)]
Is there a more clean way to get partly non-optional type as a result? Without force-unwrapping...
When we filtering out nils it's should be obvious to compiler that we will get something non-optional. Like it is in the case when we applying compactMap for example.
Here's a way without force-unwrapping that is still mostly readable:
let result = elements.compactMap { $0 as? (Int, Int?) }
Printing out result
shows that it works:
[(1, Optional(2)), (2, Optional(1)), (3, nil), (5, Optional(6)), (6, Optional(5))]
The only way without force unwrapping (!
) I could think of is:
let result = elements.compactMap { (x, y) in x.map { ($0, y) } }
But that sacrifices readability. I would just keep the force unwrapping to be honest. It's not an "absolute evil" thing. Sometimes you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With