Functor and Monad in Swift
We’ve seen what
map
can do when implemented on a container type, likeOptional
,Array
orResult
. To recap, it allows us to get a new container, where the value(s) wrapped inside are transformed according to a function. So what’s a Functor you may ask? A Functor is any type that implementsmap
. That’s the whole story.[…]
In the earlier example, we used the transformation function to return another value, but what if we wanted to use it to return a new
Result
object? Put another way, what if the transformation operation that we’re passing tomap
can fail with an error as well?[…]
And with that, we turned our
Result
type into a Monad! A Monad is a type of Functor. A type which, along withmap
, implements aflatMap
function (sometimes also known asbind
) with a signature similar to the one we’ve seen here.