Skip to content

Instantly share code, notes, and snippets.

@cobalamin
Last active August 29, 2015 14:20
Show Gist options
  • Save cobalamin/dd88a1755323798a1dfe to your computer and use it in GitHub Desktop.
Save cobalamin/dd88a1755323798a1dfe to your computer and use it in GitHub Desktop.
Swift Optional chaining == flatMap
// 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