4

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

5
  • you can't change the type of the same variable you have to create another 1 Commented Jul 8, 2020 at 11:47
  • try below answer but as pre to know it's not compiled Commented Jul 8, 2020 at 11:48
  • reduce flatMap compactMap return a value and you don't assign it to another variable so your first 3 lines are useless Commented Jul 8, 2020 at 11:53
  • @ Sh_Khan I've edited the question kindly have a look Commented Jul 8, 2020 at 11:56
  • below is the answer check it Commented Jul 8, 2020 at 11:57

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

You can try

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

Also

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.