CompactMap is a combination of map and filter. Learn how it takes a closure that returns some type. Like map it may be a different type from the collection originally contained. However, the return type of the closure is an Optional. So if the closure returns nil it filters it out. In that way, it maps and filters.
- [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 going to return an option.…
- What are closures?
- Closures and function types
- Basic higher-order functions, including sort and forEach
- Powerful higher-order functions, including map and reduce
- Passing functions
- Closure optimizations
- Higher-order functions on sets, dictionaries, and strings