假设我们有一个可选定义的数组:
var arrayOfOptionals: [String?] = ["Seems","like","an",nil,"of","optionals"]
我可以用简短的方式强制解开它:var arrayForCrash = arrayOfOptionals.map {$ 0! }
但是这会让应用程序崩溃,有没有其他的简短方法(没有显式解包)我可以如何解开一个可选的数组?
该解决方案将为您提供一个新数组,其中所有值都解开,所有的nil都被过滤掉。
原文链接:https://www.f2er.com/swift/320633.html使用flatMap的新解决方案(需要Swift 2.0):
let arrayOfOptionals: [String?] = ["Seems","optionals"] let arrayWithNoOptionals = arrayOfOptionals.flatMap{ $0 }
旧解决方案
let arrayOfOptionals: [String?] = ["Seems","optionals"] let arrayWithNoOptionals = arrayOfOptionals.filter{ $0 != nil }.map{ $0! }