Optional, Functor and Monad

What is optional?

The definition of Optional is:

It is a enum type, which has two possible values. We can consider it as Schrödinger’s cat. some means the box contains a wrapped value (😺 is alive). none means the box contains nothing (nothing alive in here 💀). We can only ensure there is a value in the box (A living 😺 in there) by opening it. This is just what if let does for us. if let opens the box, fetch back the unwrapped value.

? in Type? and nil are just syntax sugars for Optional<Type> and Optional<Type>.none.

What is functor?

Functor is a type with a map function. It takes a normal function, which transforms the wrapped value, and returns another functor.

public func map<U>(_ transform: @noescape (Wrapped) throws -> U) rethrows -> Functor<U>

Optional is a functor.

What is monad?

Monad is a type with a flatMap function. It takes a function, which transforms the wrapped value to a Monad, and returns another Monad.

public func flatMap<U>(_ transform: @noescape (Wrapped) throws -> Monad<U>) rethrows -> Monad<U>

Optional is also a monad.

Where to go from here?

In this post, we demystify Optional, functor and monad. Optional is a monad which we use everyday in Swift. We love it, hate it and cannot live without it.

In the next posts, we will see more useful monads in Swift, and how they can help us to write cleaner code.