Charlie Fish
Charlie Fish

Reputation: 20546

Swift Array Map Skip Value

Say I have the following code.

let myArray = [1,4,5,8,9,13,14,15]
let numbers = [4,8,13,15]
let finalArray = myArray.map({id in numbers.first(where: {$0 == id})!})

But I get an error because sometimes numbers.first(where: {$0 == id}) returns nil sometimes and can't be unwrapped.

I know this isn't the best example but it's the simplest example to explain what I'm trying to do.

My goal in this example is to have finalArray be [4,8,13,15]. So IF numbers.first(where: {$0 == id}) is nil just skip that value.

Is this possible with map in Swift? Or does the returned array length have to equal the array we are running map on?

Quick note. My example is very simple and in practice my problem is more complicated. I have my reasons for wanting to use map because it is an easy way to get a new array based on another array.

Upvotes: 0

Views: 4205

Answers (2)

pwnell
pwnell

Reputation: 171

To expand on Rashwan L's answer, I believe the Swift 4 version is as follows:

let finalArray = myArray.compactMap({ id in numbers.first(where: {$0 == id}) })

Upvotes: 3

Rashwan L
Rashwan L

Reputation: 38833

As @LeoDabus pointed out you should use flatMap instead of map in this situation. The reason is because flatMap can return nil since flatMap has the return type U? while map has the return type of U and can´t handle nil.

So this line, can handle nil with flatMap:

let finalArray = myArray.flatMap({ id in numbers.first(where: {$0 == id}) })

Upvotes: 3

Related Questions