Learn how flatMap is no longer a higher order function on collections. The version of this function on collections was renamed compactMap. However flatMap still exists in Swift on Optionals. You can call flatMap on an Optional and pass in a closure. The closure takes the item and returns an item of any type or nil.
- [Narrator] Now we're going to talk just a minute…about FlatMap.…So FlatMap is what CompactMap used to be called…in previous versions of Swift.…Now, it's called CompactMap for all the collections,…but FlatMap is still around.…You can call FlatMap on Optionals.…You can think of it as a single element mapping,…or a single element compact mapping actually,…because you can return nil.…So you have an Optional…and you want to get something out of it,…but you may return a nil, you can use FlatMap.…To be honest, I don't use it that often,…but I definitely want to cover it.…
One should be aware of what it does.…So let's say we have, let's take a simple example.…On line 19 I'll type let someVal and I'll declare it…as a string Optional, equal a string that says, some string.…And then I want to map that to something…so I'll say let someMap equal someVal.flatMap.…It's the same signature, it takes a string,…'cause that's what this is.…It's a string optional,…so it's going to return a string in there.…
So it's going to unwrap it.…
- 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