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

前端之家收集整理的这篇文章主要介绍了在Swift中执行地图时跳过项目?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在将地图应用到试用它的字典中.如果映射项无效,我想跳过迭代.

例如:

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

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

只需用flatMap()替换map():
  1. extension SequenceType {
  2. /// Returns an `Array` containing the non-nil results of mapping
  3. /// `transform` over `self`.
  4. ///
  5. /// - Complexity: O(*M* + *N*),where *M* is the length of `self`
  6. /// and *N* is the length of the result.
  7. @warn_unused_result
  8. public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
  9. }

尝试? …如果调用抛出错误,则返回nil,所以那些
结果中将省略元素.

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

  1. enum MyError : ErrorType {
  2. case DivisionByZeroError
  3. }
  4.  
  5. func inverse(x : Double) throws -> Double {
  6. guard x != 0 else {
  7. throw MyError.DivisionByZeroError
  8. }
  9. return 1.0/x
  10. }
  11.  
  12. let values = [ 1.0,2.0,0.0,4.0 ]
  13. let result = values.flatMap {
  14. try? inverse($0)
  15. }
  16. print(result) // [1.0,0.5,0.25]

对于Swift 3,将ErrorType替换为Error.

对于Swift 4,请使用compactMap

猜你在找的Swift相关文章