Reputation: 725
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
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
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