ambientlight ambientlight - 1 year ago 145
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 = { $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 Source

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! }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download