Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change type to non-optional after get rid of nils by applying filter

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.

like image 476
Roman Avatar asked Sep 04 '20 06:09

Roman


Video Answer


2 Answers

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))]
like image 167
TylerP Avatar answered Oct 13 '22 22:10

TylerP


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.

like image 45
Sweeper Avatar answered Oct 13 '22 20:10

Sweeper