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

后端 未结 5 1995
野的像风
野的像风 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条回答
  •  Happy的楠姐
    2021-02-05 06:04

    You could use reduce:

    let flattened = possibles.reduce([Int]()) { 
            if let x = $1 { return $0 + [x] } else { return $0 } 
        }
    

    You are still kind of declaring the type, but it's slightly less obtrusive.

提交回复
热议问题