Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: shortcut unwrapping of array of optionals

Tags:

swift

Assume we have an array of optionals defined:

var arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"] 

I can force unwrap it in a short way: var arrayForCrash = arrayOfOptionals.map { $0! }

But that will make app to crash, is there any other short way(without explicitly unwrapping) how I can unwrap an array of optional?

like image 452
ambientlight Avatar asked Aug 31 '14 06:08

ambientlight


People also ask

How do I unwrap an array in Swift?

I can force unwrap it in a short way: var arrayForCrash = arrayOfOptionals. map { $0! }


2 Answers

This solution will get you a new array with all values unwrapped and all nil's filtered away.

Swift 4.1:

let arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"] let arrayWithNoOptionals = arrayOfOptionals.compactMap { $0 } 

Swift 2.0:

let arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"] let arrayWithNoOptionals = arrayOfOptionals.flatMap { $0 } 

Swift 1.0:

let arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"] let arrayWithNoOptionals = arrayOfOptionals.filter { $0 != nil }.map { $0! } 
like image 92
Cenny Avatar answered Oct 25 '22 13:10

Cenny


Since it is an array of optionals, it is possible some of the entries are nil. Instead of force unwrapping with !, use the nil coalescing operator to turns nils into empty strings.

let arrayOfOptionals: [String?] = ["This", "array", nil, "has", "some", "nils", nil]  let array:[String] = arrayOfOptionals.map{ $0 ?? "" } // array is now ["This", "array", "", "has", "some", "nils", ""] 
like image 26
vacawama Avatar answered Oct 25 '22 13:10

vacawama