gpt4 book ai didi

swift - 当其中一个元素无法快速转换时中止转换

转载 作者:行者123 更新时间:2023-11-30 10:35:33 24 4
gpt4 key购买 nike

在 swift 中,我们有针对数组的高阶函数,如 map、filter、reduce 等

但是如果我有一个数组,例如 [Any] = [1, 2, 3, "1"]。

我希望将此数组转换为 Int 数组。但由于数组中有“1”,我的逻辑是接受整个数组无效,我将其映射到一个空数组。

在这种情况下我该如何使用更高的功能呢?

过滤很容易

let array: [Any] = [1, 2, 3, "1"]
let filtered = array.compactMap{ $0 as? Int}
/// prints [1, 2, 3]

但我希望最终结果是[],而不是[1,2,3]。

如何使用高阶函数实现这一点?

最佳答案

紧凑 map

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

所以你不能使用compactMap返回你想要的东西

let array: [Any] = [1, 2, 3, "1"]


for case let element in array {
if let _ = element as? Int {
continue
} else {
print("\(element) isn't an Int, so array is invalid")
break
}
}

关于swift - 当其中一个元素无法快速转换时中止转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127648/

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