swift - 在 Swift 中执行 map 时跳过项目?

标签 swift generics try-catch swift2

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

例如:

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

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

最佳答案

只需将 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,因此那些 结果中将省略元素。

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

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

关于swift - 在 Swift 中执行 map 时跳过项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36293394/

相关文章:

java - 如何实例化 List<MyType>?

c++ - MongoDB C++ 驱动程序不抛出连接错误

typescript - 如何在 TypeScript 中创建一个适用于数字和字符串的通用加法运算符

scala - @uncheckedVariance 在 Kotlin 中?

java - 如何处理 JsonMappingException try catch

java - 我的 try catch 循环陷入无限循环,每次都应该提示用户输入

ios - 允许在 UISearchController 处于事件状态时选择单元格

ios - Swift - Xcode 无法识别现有的成员变量

Swift 中等效的 Java 接口(interface)

ios - 标签的内容正在堆栈 View 中被裁剪