I\'m a little confused around flatMap (added to Swift 1.2)
Say I have an array of some optional type e.g.
let possibles:[Int?] = [nil, 1, 2, 3, nil, nil
Since this is something I seem to end up doing quite a lot I'm exploring a generic function to do this.
I tried to add an extension to Array so I could do something like possibles.unwraped
but couldn't figure out how to make an extension on an Array. Instead used a custom operator -- hardest part here was trying to figure out which operator to choose. In the end I chose >!
to show that the array is being filtered >
and then unwrapped !
.
let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5]
postfix operator >! {}
postfix func >! (array: Array) -> Array {
return array.filter({ $0 != nil }).map({ $0! })
}
possibles>!
// [1, 2, 3, 4, 5]