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

Viewed 1038

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

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

You can try

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

Also

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