在Swift中执行地图时跳过项目? [英] Skip item when performing map in Swift?

查看:154
本文介绍了在Swift中执行地图时跳过项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm applying a map to a dictionary that has a try in it. I'd like to skip the iteration if the mapped item is invalid.

例如:

For example:

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

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

In the above sample, if anotherFunc returns nil, how to escape the current iteration and move on to the next? That way, it would not contain the items that are nil. Is this possible?

推荐答案

只需将 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]
}

试试? ... 如果调用抛出错误,则返回 nil ,因此这些
元素将在结果中被省略。

try? ... returns nil if the call throws an error, so those elements will be omitted in the result.

一个自包含的示例,仅用于演示目的:

A self-contained example just for demonstration purposes:

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 ,用 Error 替换 ErrorType

这篇关于在Swift中执行地图时跳过项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆