Map and flatmap
Let’s say you want to create an array of pets that are owned by the team. First off, you need to create an array of team members:
let team = [janie, tammy, felipe]
You want to iterate through this array and extract all pet names. You could use a
for loop, but you’ve already learned a better way to do this: map.
let petNames = team.map { $0.pet?.name }
This creates a new array of pet names by pulling out the pet name from each team member in the array. You want to see what these values are, so why not print them out:
for pet in petNames { print(pet)
}
Look at the output for this print statement:
Optional("Delia") Optional("Evil Cat Overlord") nil
Ew! That doesn’t look right. Instead of having a nice list of names, you have a bunch of optional values and even a nil! This won’t do at all.
You could take this array, filter it and then do another map to unwrap all the values that are not nil, but that seems rather convoluted. Iterating through an array of optional values that you need to unwrap and ensure are not nil is a really common thing.
There is a better way of accomplishing this task: flatMap. Try out the following:
let betterPetNames = team.flatMap { $0.pet?.name }
for pet in betterPetNames { print(pet)
}
You should see a far more useful and user friendly output:
Delia
Evil Cat Overlord
In general, flatMap does a regular map operation and then “flattens”, or simplifies, the results. In this case, you’re using flatMap to flatten the return type [Optional<String>] into the simpler type [String]. Another common use of flatMap is to turn an array of arrays into a single array.
So far you have learned how to do some informal error handling. Up next, you’ll learn about the Error protocol to do some formal error handling.