Last active
May 31, 2016 16:23
-
-
Save jmnavarro/fa47e21e837c9c904708347cd70c6505 to your computer and use it in GitHub Desktop.
FlatMap magic with optionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var number: Int? | |
number.flatMap { | |
// this is never executed | |
print($0) | |
} | |
number = 1 | |
number.flatMap { | |
// this is executed! | |
print($0) | |
} | |
// Same with closures | |
// --------- | |
var closure: (() -> ())? | |
closure.flatMap { | |
// this is never executed | |
$0() | |
} | |
// Set value | |
closure = { | |
print("hello flatMap") | |
} | |
closure.flatMap { | |
// this is now ejecuted! | |
$0() | |
} | |
// So, instead of "if" or "if let" with optionals, you can flatMap them | |
// Instead of this... | |
if let n = number { | |
// use n | |
} | |
// You can do this... | |
number.flatMap { | |
// use $0 | |
print($0) | |
} | |
// It's even better if you need to call a function when the value is not nil | |
func my_function(n: Int) { | |
// bla bla bla | |
} | |
// Instead of this... | |
if let n = number { | |
my_function(n) | |
} | |
// You can do this (call the function only when there's a value) | |
number.flatMap(my_function) | |
// Same with closures... | |
// ------------ | |
if let c = closure { | |
// use c() | |
} | |
closure.flatMap { | |
$0() | |
} | |
// Btw, for closures, you have a better shortcut: | |
closure?() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment