J.Doe
J.Doe

Reputation: 725

Safely unwrap optional value

I am using this code to create a new array of colors. Everything is working fine.

But I don't want to force unwrap $0.color! because the app crashes sometimes when the value is nil.

How can I leave it as an optional? If I just delete the ! I get an error asking me to unwrap it.

let newArray = oldDict.map{ UIColor(hexString: $0.color!)}

Upvotes: 2

Views: 557

Answers (2)

Rajmund Zawiślak
Rajmund Zawiślak

Reputation: 942

You should use compactMap instead of map, because compactMap does not return elements which are nil and in closures just unwrap color with guard let statement

let newArray = oldDict.compactMap {
    guard let color = $0.color else {
        return nil
    }

    return UIColor(hexString: color)
}

Upvotes: 6

0x416e746f6e
0x416e746f6e

Reputation: 10126

Here are some ways to do that:

let newArray1 = oldDict
    .filter({ $0.color != nil })
    .map({ UIColor(hexString: $0.color! )})

let newArray2 = oldDict
    .flatMap({ $0.color })
    .map({ UIColor(hexString: $0) })

Upvotes: 2

Related Questions