ambientlight ambientlight - 4 months ago 27
Swift Question

Swift: shortcut unwrapping of array of optionals

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?

Answer

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

New solution that utilize flatMap (requires Swift 2.0):

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

Old Solution:

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