Skip item while executing map in Swift?

I apply a map to a dictionary that has a try . I would like to skip the iteration if the displayed item is not valid.

For instance:

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

In the above example, if anotherFunc returns nil , how to avoid the current iteration and move on to the next? This way it will not contain nil elements. Is it possible?

+5
source share
1 answer

Just replace map() with 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] } 

try? ... try? ... returns nil if the call causes an error, so those elements will be omitted as a result.

Do-it-yourself example for demonstration purposes only:

 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] 

For Swift 3, replace ErrorType with Error .

+16
source

Source: https://habr.com/ru/post/1246014/


All Articles