Last active
August 29, 2015 14:20
-
-
Save cobalamin/dd88a1755323798a1dfe to your computer and use it in GitHub Desktop.
Swift Optional chaining == flatMap
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
// An (admittedly silly) demonstration of how optional chains in Swift | |
// are equivalent to flatMapping over each optional. | |
// | |
// You can, in your mind, replace every `?.x` by a `flatMap { $0.x }` call. | |
class Peel { | |
var color: String | |
init(color: String) { self.color = color } | |
} | |
class Banana { | |
var peel: Peel? | |
} | |
class Monkey { | |
var banana: Banana? | |
} | |
let monkey = Monkey() | |
monkey.banana = Banana() | |
monkey.banana?.peel = Peel(color: "brown") | |
var s1 = monkey.banana?.peel?.color // "brown" - equivalent to next line | |
var s2 = monkey.banana.flatMap({ $0.peel }).flatMap({ $0.color }) // "brown" | |
s1.debugDescription // Optional("brown") | |
s2.debugDescription // Optional("brown") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment