Swift:快捷方式展开可选数组
假设我们定义了一个可选数组:
var arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"]
我可以在短时间内强行打开包装: 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! }
以上是 Swift:快捷方式展开可选数组 的全部内容, 来源链接: utcz.com/qa/401000.html