Swift flatMap gives unexpected result while using with optional array

后端 未结 3 949
半阙折子戏
半阙折子戏 2021-02-03 12:58

We have an array of the Person objects and each object has another array of String, which is optional. We want the consolidated list of car names in our society.



        
3条回答
  •  北恋
    北恋 (楼主)
    2021-02-03 13:20

    Why let cars: [String] is different from let cars: [String]? with flatMap ?

    There are two flavours of flatMap on sequences;

    1) one that flattens out sequences returned from the closure passed to it,

    2) one that filters out nils from the closure passed to it (note this overload is soon to be renamed to compactMap to avoid confusion as @krunal mentioned on comment)

    In your code you’re using the nil filtering overload, so the nils in your array are filtered out. It won’t however do any flattening of the nested arrays. You could call flatMap again to achieve that.

    like

    let flatmapArray = personsArray.flatMap{$0.cars}.flatMap{$0}
    print(flatmapArray)
    

提交回复
热议问题