gpt4 book ai didi

Swift:可选数组的快捷展开

转载 作者:IT王子 更新时间:2023-10-29 05:02:18 24 4
gpt4 key购买 nike

假设我们定义了一个可选数组:

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:可选数组的快捷展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com