Slide 76
Slide 76 text
let monkeyResult =
database.monkey("Peepers")
let tricycleResult =
monkeyResult.flatMap { (monkey: Monkey) in
return database.tricycle(monkey)
}
let brandNameResult =
tricycleResult.map { (tricycle: Tricycle) in
return tricycle.brandName
}
return brandNameResult
- First, we grab the result of reading “Peepers” from the database.
- (click) Then, we grab a tricycle using that result.
- (click) flatMap takes a closure that, given a monkey, returns a Result, which is either a Tricycle or an error.
- (click) The closure is *only* run if `monkeyResult` is a success. If it’s a *failure*, then we have no monkey to pass to the
closure, and it’s never executed.
- (click) Next, we grab the brand name of the tricycle.
- (click) The map method takes a closure that, given a tricycle, returns that tricycle’s brand name. The ‘brandName’ method
can’t fail—it doesn’t return a Result, it returns a String.
- (click) Once again, this closure is *not run* if the tricycle result is a failure—that is, if we’re already on our failure track.
- (click) The only way we can be on our success track is if Peepers is in the database, and if his tricycle is also in the
database.
- (click) Finally, we return the brand name result.