假设我们定义了一个可选数组:
var arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"]
我可以在短时间内强行打开包装: var arrayForCrash = arrayOfOptionals.map { $0! }
var arrayForCrash = arrayOfOptionals.map { $0! }
但这会使应用程序崩溃,是否还有其他短途方法(无需显式展开)如何展开可选数组?
此解决方案将为您提供一个新数组,其中所有值均已解包且所有nil均被滤除。
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! }