How to use swift flatMap to filter out optionals from an array

后端 未结 5 1935
野的像风
野的像风 2021-02-05 05:14

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         


        
5条回答
  •  不知归路
    2021-02-05 06:10

    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]
    

提交回复
热议问题