Copy and paste the swift code below into a playground to experiment.
This is a very close emulation of Functor and Monad typeclasses in swift. However, it is very fragile (i.e. easy to crash the compiler).
For example, instance methods of fmap
will run fine, but attempting to use a globally defined fmap
that acts on Functor
types will cause a crash. Similarly for bind
. Unfortunately this means we cannot define the nice infix operator versions of these functions.
In case anyone else is wondering why this works, note the following also works for fmap and is simpler -- the associatedtype B / typealias B = Any isn't actually necessary.
It's essentially relying on covariance of the functor -- [B] being a subtype of [Any], B? of Any? etc -- to allow a more specific return type to be inferred for fmap for specific calls, while still allowing those implementations to conform with the type of the protocol method.