From the course: Learning Higher-Order Functions with Swift

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

CompactMap

CompactMap

From the course: Learning Higher-Order Functions with Swift

Start my 1-month free trial

CompactMap

- [Narrator] Now we're going to get just a teeny bit more complicated, not really much more. Let's say you have your array of names, and you want to map them to the lengths, but only for the ones that are longer than four. So you could do a filter and filter out those items, and then you could do a map to ints. So let's look at that. So back over in our playground, I got the longer names and then I can say let lens equal longer names dot map and then I'm going to pass in val one, now return type is an int, and I'm going to return the val one dot count, and now what I have if I print out the lens, is I'm going to have an array of the lengths, but only of the longer names. So I filtered, and then I mapped. There's got to be an easier way, I know that's what you're saying to yourself, and you're right. So Compact Map combines Map and Filter. So it's very much the same as a Map, but it returns an Optional. So instead of returning BOOL for yes to keep it, and false to filter it out, you're…

Contents