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

后端 未结 5 1992
野的像风
野的像风 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 05:54

    Related to the question. If you are applying flatMap to an optional array, do not forget to optionally or force unwrap your array otherwise it will call flatMap on Optional and not objects conforming to Sequence protocol. I made that mistake once, E.g. when you want to remove empty strings:

    var texts: [String]? = ["one", "two", "", "three"] // has unwanted empty string
    
    let notFlatMapped = texts.flatMap({ $0.count > 0 ? $0 : nil })
    // ["one", "two", "", "three"], not what we want - calls flatMap on Optional
    
    let flatMapped = texts?.flatMap({ $0.count > 0 ? $0 : nil })
    // ["one", "two", "three"], that's what we want, calls flatMap on Array
    

提交回复
热议问题