swift - 是否可以中止 Swift 集合上的映射函数?

标签 swift map-function codable

我们有一个案例,我们被交给了一个类型为 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});
}

这是可能的,还是我们原来的方式是正确的/唯一的方式?

最佳答案

这是一个使用 mapthrows 的解决方案。

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/

相关文章:

swift - 如何在静态方法中等待回调代码完成?

javascript - 将数字字符串映射到返回 NaN 的整数

json - 从 API 解码 JSON - Swift 5

swift - Codable 类不符合 Decodable 协议(protocol)

Swift 4 Codable 数组的

ios - SiriKit 和 CNContactStore

xcode - 如何使用 XCTest 在 Xcode 中测试 Swift 文件而无需构建整个应用程序?

ios - 简单的语音识别 Swift?

arrays - 在 APL 中使用带有 without 函数的 each 运算符

recursion - 鸭图到底有什么作用?