Reputation: 522
I've only basic knowledge in Swift.
I want to change var dataSource:[[CustomModel?]]?
into [CustomModel]
.
I tried following Methods
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
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
Upvotes: 5
Reputation: 100533
You can try
var arr:[CustomModel] = dataSource?.flatMap { $0 } ?? []
Also
var arr:[CustomModel] = dataSource?.flatMap { $0 }.compactMap{ $0 } ?? []
Upvotes: 3