Change type to non-optional after get rid of nils by applying filter
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.