The code works, but the type of the generic is not guaranteed at compile time. FunctorResult could be anything at all. There is no compile-time obligation for the code to return a Dictionary<KeyType, P>.
The more canonical example of a Functor is really the Optional. The mapping method for an optional looks like this:
func fmap(f: A -> B) -> Optional<B> {
switch self {
case Some(let a):
return Some(f(A))
case None:
return None
}
}
However, with your protocol, I can define the mapping function for the Optional as:
func fmap(f: A -> B) -> B[] {
switch self {
case Some(let a):
return [f(A)]
case None:
return B[]()
}
}
This would pass the type-checker, but is not what a Functor does.
The more canonical example of a Functor is really the Optional. The mapping method for an optional looks like this:
However, with your protocol, I can define the mapping function for the Optional as: This would pass the type-checker, but is not what a Functor does.