swift - 当元素之一无法快速转换时中止转换
问题描述
在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]。
我如何使用高阶函数来实现这一点?
解决方案
假设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)) ?? []
推荐阅读
- c# - C#:对 exe 使用大图标
- javascript - 是否可以通过外部 .js 文件访问 Handlebar 变量?
- reactjs - 如何解决未安装的组件?
- sharepoint - 如何在 SharePoint Online 中修改 AppCatalog 网站的权限
- c++ - 有没有办法在矢量类中显示所有保存的对象?
- php - 在 PHP 中从未知对象获取数据的另一种方法
- string - 将值复制到另一个 StatefulWidget
- python - 如何将函数作为参数放入现有函数
- javascript - 如何向服务器发送实时数据?
- java - 为什么我的 JFrame 的背景不会变黑?