I'm applying a map to a dictionary that has a try
in it. I'd like to skip the iteration if the mapped item is invalid.
For example:
func doSomething<T: MyType>() -> [T]
dictionaries.map({
try? anotherFunc($0) // Want to keep non-optionals in array, how to skip?
})
}
In the above sample, if anotherFunc
returns nil
, how to escape the current iteration and move on to the next? That way, it would not contain the items that are nil
. Is this possible?
Just replace
map()
byflatMap()
:try? ...
returnsnil
if the call throws an error, so those elements will be omitted in the result.A self-contained example just for demonstration purposes:
For Swift 3, replace
ErrorType
byError
.For Swift 4 use
compactMap