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?
I can force unwrap it in a short way: var arrayForCrash = arrayOfOptionals. map { $0! }
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! }
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", ""]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With