首页 > 解决方案 > 当元素之一无法快速转换时中止转换

问题描述

在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]。

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

标签: swift

解决方案


假设array as? [Int] ?? []不适用(例如,您需要应用更复杂的转换),您可能会throw出现错误。

enum ConversionError: Error {
    case notAllValuesWereInts
}

func convertOrThrow(_ input: Any) throws -> Int {
    switch input {
        case let int as Int: return int
        default: throw ConversionError.notAllValuesWereInts
    }
}

let array: [Any] = [1, 2, 3, "1"]
let ints: [Int]
do {
    ints = try array.map(convertOrThrow)
} catch {
    ints = []
}
print(ints)

在这种error用于控制流的情况下,不携带任何有用信息,您可以使用它try?来简化事情:

let array: [Any] = [1, 2, 3, "1"]
let ints = (try? array.map(convertOrThrow)) ?? []

推荐阅读