我们有一个案例,我们被交给了一个类型为 Array<Any>
的对象。我们需要将其转换为 Array<Codable>
.如果原始数组中的任何项目不遵守 Codable
,然后我们希望整个过程中止并返回 nil。
或者当前的方法是手动遍历所有内容,一路测试,就像这样......
func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{
var codableArray = Array<Codable>()
for item in sourceArray{
guard let codableItem = item as? Codable else {
return nil
}
codableArray.append(codableItem)
}
return codableArray
}
但是,我想知道是否有更简单的方法使用 map
执行此操作命令,但如果无法映射任何元素,则需要将其短路。我不确定这是否可能。
例如,这个伪代码...
func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{
return sourceArray.map({ $0 as? Codable});
}
这是可能的,还是我们原来的方式是正确的/唯一的方式?
最佳答案
这是一个使用 map
和 throws
的解决方案。
func makeCodable(sourceArray: [Any]) -> [Codable]? {
enum CodableError: Error {
case notCodable
}
let res: [Codable]? = try? sourceArray.map {
guard let codable = $0 as? Codable else {
throw CodableError.notCodable
}
return codable
}
return res
}
let res = makeCodable2(sourceArray: [5, 6.5, "Hi", UIView()])
print(res) // nil
下面是一个变体,它使 makeCodable
抛出并返回一个非可选数组:
enum CodableError: Error {
case notCodable
}
func makeCodable(sourceArray: [Any]) throws -> [Codable] {
let res: [Codable] = try sourceArray.map {
guard let cod = $0 as? Codable else {
throw CodableError.notCodable
}
return cod
}
return res
}
do {
let res = try makeCodable(sourceArray: [5, 6.5, "Hi"])
print(res) // prints array
let bad = try makeCodable(sourceArray: [5, 6.5, "Hi", UIView()])
print(bad)
} catch {
print(error) // goes here on 2nd call
}
关于swift - 是否可以中止 Swift 集合上的映射函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724385/