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.

FlatMap

FlatMap

From the course: Learning Higher-Order Functions with Swift

Start my 1-month free trial

FlatMap

- [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…

Contents