【问题标题】:Skip item when performing map in Swift?在 Swift 中执行地图时跳过项目?
【发布时间】:2016-03-29 19:26:27
【问题描述】:

我正在将地图应用于其中包含 try 的字典。如果映射项无效,我想跳过迭代。

例如:

func doSomething<T: MyType>() -> [T]
    dictionaries.map({
        try? anotherFunc($0) // Want to keep non-optionals in array, how to skip?
    })
}

在上面的示例中,如果anotherFunc 返回nil,如何退出当前迭代并继续下一个迭代?这样,它就不会包含nil 的项目。这可能吗?

【问题讨论】:

    标签: swift generics swift2 try-catch swift2.2


    【解决方案1】:

    只需将map() 替换为flatMap()

    extension SequenceType {
        /// Returns an `Array` containing the non-nil results of mapping
        /// `transform` over `self`.
        ///
        /// - Complexity: O(*M* + *N*), where *M* is the length of `self`
        ///   and *N* is the length of the result.
        @warn_unused_result
        public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
    }
    

    try? ... 如果调用抛出错误,则返回nil,所以那些 结果中的元素将被省略。

    仅用于演示目的的独立示例:

    enum MyError : ErrorType {
        case DivisionByZeroError
    }
    
    func inverse(x : Double) throws -> Double {
        guard x != 0 else {
            throw MyError.DivisionByZeroError
        }
        return 1.0/x
    }
    
    let values = [ 1.0, 2.0, 0.0, 4.0 ]
    let result = values.flatMap {
        try? inverse($0)
    }
    print(result) // [1.0, 0.5, 0.25]
    

    对于 Swift 3,ErrorType 替换为 Error

    对于 Swift 4 使用 compactMap

    【讨论】:

    • 感谢您让我发现flatMap!我只是注意到它不适用于字典。
    • @TruMan1:我很确定确实如此。 mapflatMap 都可以应用于字典。使用键/值作为参数调用闭包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2014-10-13
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多