Anees
Anees

Reputation: 522

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]'

Upvotes: 4

Views: 2214

Answers (2)

Shashank Mishra
Shashank Mishra

Reputation: 1077

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

Upvotes: 5

Shehata Gamal
Shehata Gamal

Reputation: 100533

You can try

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

Also

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

Upvotes: 3

Related Questions