I have recently participated in a discussion where an interesting problem was brought up.
In enterprise-Scala-all-around code the ability to override default typeclass implicits seems to be high-regarded.
The problem (in Swift terminology):
Imagine a library that provides a protocol (e.g.
Serializable) and a function (e.g.
serialize). The library also provides default implementation of the protocol for some known types, including but not limited to, builtins such as
Array. Moreover, in the latter case default implementations are
Now consider a case where the end user decides, that the defaults are not good enough. Worse, the library is a readonly dependency, so no patching or ad-hoc fixes.
In Scala this problem is naturally addressed by adding additional implicit with appropriate type signature. The compiler then selects the implicit (in case if there are multiple matching the signature) from the closest namespace.
In Swift, I originally speculated, one could expect similar behavior, i.e. one could just write another
extension Array: Serializable where Element == Int in the main module (outside of the library), maybe sprinkle it with some keywords and then trust the compiler to pick it as being closer then one from the library.
I was obviously wrong as Swift forbids multiple protocol conformances.
I'm interested in knowing what would be the idiomatic approach for this case that would match the behavior in terms of flexibility.