Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Flatten Array of Array of custom Object [[CustomModel?]]?

I've only basic knowledge in Swift. I want to change var dataSource:[[CustomModel?]]? into [CustomModel].

I tried following Methods

  1. let flat = dataSource.reduce([],+)
  2. let flat = dataSource.flatMap { $0 }
  3. let flat = dataSource.compactMap{ $0 }
  4. let flat = dataSource.Array(dataSource.joined())

I'm getting error

Cannot convert value of type '[FlattenSequence<[[CustomModel?]]>.Element]' (aka 'Array<Optional< CustomModel >>') to expected argument type '[CustomModel]'

like image 944
Anees Avatar asked Sep 04 '25 16:09

Anees


2 Answers

You need to flat the nested array first using flatMap{}, then in order to get the non-optional value use compactMap{}. Suppose the input array is [[Int?]]

let value:[Int] = dataSource.flatMap{$0}.compactMap{ $0 } //Correct

The other option will give an error -

let value:[Int] = dataSource.flatMap{ $0 } ?? [] //Error

//Correct enter image description here

//Wrong enter image description here

like image 180
Shashank Mishra Avatar answered Sep 07 '25 13:09

Shashank Mishra


You can try

var arr:[CustomModel] = dataSource?.flatMap { $0 } ?? [] 

Also

var arr:[CustomModel] = dataSource?.flatMap { $0 }.compactMap{ $0 } ?? [] 
like image 36
Sh_Khan Avatar answered Sep 07 '25 13:09

Sh_Khan