在Swift中执行地图时跳过项目?

Tru*_*an1 11 generics try-catch swift swift2 swift2.2

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

例如:

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

在上面的示例中,如果anotherFunc返回nil,如何转义当前迭代并继续下一步?这样,它就不会包含那些项目nil.这可能吗?

Mar*_*n R 24

只需替换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]
}
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)

对于Swift 3,替换ErrorTypeError.

对于Swift 4使用compactMap

  • @ TruMan1:我很确定它确实如此.`map`和`flatMap`都可以应用于字典.使用key/value作为参数调用闭包. (3认同)