在Swift中执行地图时跳过项目?
发布时间:2020-12-14 05:26:38 所属栏目:百科 来源:网络整理
导读:我正在将地图应用到试用它的字典中.如果映射项无效,我想跳过迭代. 例如: func doSomethingT: MyType() - [T] dictionaries.map({ try? anotherFunc($0) // Want to keep non-optionals in array,how to skip? })} 在上面的示例中,如果anotherFunc返回nil,如
我正在将地图应用到试用它的字典中.如果映射项无效,我想跳过迭代.
例如: func doSomething<T: MyType>() -> [T] dictionaries.map({ try? anotherFunc($0) // Want to keep non-optionals in array,how to skip? }) } 在上面的示例中,如果anotherFunc返回nil,如何转义当前迭代并继续下一步?这样,它就不会包含零项.这可能吗?
只需用flatMap()替换map():
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |