Optional in Swift 2

Meet Optional. You have seen these

You will see lots of optional throughout Foundation and UIKit. It represents a context in which there is a value, or there is not.

In Objective, you can have a pointer which can points to something, or nil. But Optional makes it more generic. You can now have `Int?, UIImage?, String?, UIWindow? …`

The idea of optional type is not new, you may have seen it through `data Maybe a = Nothing | Just a` in Haskell, `enum Option<T> { None, Some(T) }` in Rust, `Optional<T>` in Java 8, `System.Nullable<T>` in C#, …

In Swift, optional is all about `?` and `!`. The latter is for the lazy one

Optional is enum

Optional is implemented using associated type enum and generic


When you see

It is actually


When you see

It is actually

Forced Unwrapping

You can use `!` to forcibly unwrap an optional. If there isn’t a value, it will crash `fatal error: unexpectedly found nil while unwrapping an Optional value`


Forced Unwrapping operator `!` is implemented like this

Implicitly Unwrapped Optionals

Optional is good, but you need to check for its value every time you need to use

In case you ‘re sure that the optional always has a value, you can use `!` to define `Implicitly Unwrapped Optionals`, which is an optional that automatically unwraps its value when you use it

Implicitly Unwrapped Optionals are Optionals, so you can check for nil and use optional binding

Optional in collection

Because optional is an enum, we can have collection of values and nils

Optional binding

We can use optional binding through `if let`. Even cooler, Swift now support multiple optional binding

Double optional

Swift has special syntax for double optional, that is `??`

Double optional is also a result of a this cast

Nil Coalescing Operator

> The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

The right hand of `??` is actually a closure

It can be chained

It works in string interpolation, too

It is implemented like this

Optional chaining

Optional might be nil, so querying for its methods, properties, subscripts will return another optional

Optional delegate

A delegate might be nil, and it might not implement optional methods. So we must use `?` when calling it

Optional callback

A callback might be nil

Optional pattern

> The new optional pattern, myValue?, is equivalent to .Some(myValue) for optionals

If you have an optional enum

You can ask for the case

You can ask for the value associated with the case

Of course, it works with `switch`, too

> An optional pattern matches values wrapped in a Some(Wrapped) case of an Optional<Wrapped> or ImplicitlyUnwrappedOptional<Wrapped> enumeration

These are equivalent

> The optional pattern provides a convenient way to iterate over an array of optional values in a for-in statement, executing the body of the loop only for non-nil elements.


There are `as?` and `as!`, see [Type Casting in Swift 2](http://www.fantageek.com/blog/2015/09/23/type-casting-in-swift/)


Failable Initializers

> A failable initializer creates an optional value of the type it initializes

Swift also supports `The init! Failable Initializer`


`try?` tries to perform an operation that may throw, returns an optional containing the returned value if succeeded. `try!` does the same, but you get an Implicitly Unwrapped Optional

Functional optional

Optional is a functor, applicative functor, and monad

Note that all these methods are implemented as extension on Optional, see my [gist](https://gist.github.com/onmyway133/48c969c8baf4e7e77ee0)


> If self == nil, returns nil. Otherwise, returns f(self!).

It is implemented like this


> Returns nil if self is nil, f(self!) otherwise.

Let ‘s use `countCharactersIfNotEmpty`, a function returning nil if it receives empty string. Yeah, it does not like empty string

It is implemented like this

map vs flatMap

Note that in `map`, `f` is of type `Wrapped -> U`, while in `flatMap`, `f` is of type `Wrapped -> U?`

If you use `map` with `Wrapped -> U?`, you ‘ll get double optional

`flatMap` can also be implemented using `map + flatten`, hence the name `flatMap`. As you already know, it is called `Forced Unwrapping`


Here is how Optional works like applicative functor, note that `f` is of type `(Wrapped -> U)?`

This is how it is implemented


- [Option type](https://en.wikipedia.org/wiki/Option_type)
- [Swift 2: Control Flow Pattern Matching Example](http://austinzheng.com/2015/09/23/pmatch-control-flow/)
- [Implementing printing versions of “try?” and “try!” — on steroids! in #swiftlang](http://ericasadun.com/2015/11/05/implementing-printing-versions-of-try-and-try-on-steroids-in-swiftlang/)
- [Match Me if you can: Swift Pattern Matching in Detail](http://appventure.me/2015/08/20/swift-pattern-matching-in-detail/#sec-4-1)
- [What is an Optional in Swift](http://www.drewag.me/posts/what-is-an-optional-in-swift)
- [Swift 2.0: Map and FlatMap Demystified](http://www.uraimo.com/2015/10/08/Swift2-map-flatmap-demystified/)
- [The Power Of Map And FlatMap Of Swift Optionals](http://blog.xebia.com/the-power-of-map-and-flatmap-of-swift-optionals/)
- [Functor and Monad in Swift ](http://www.javiersoto.me/post/106875422394)
- [Swift Functors, Applicatives, and Monads in Pictures](http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/)
- [Matching with Swift’s Optional Pattern](http://www.figure.ink/blog/2015/12/6/matching-with-swifts-optional-pattern)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.