vendredi 30 avril 2021

When to use type erasure in Swift?

There are already a lot of questions on how to do type erasure in Swift, and I've seen type erasure often described as an important pattern for working with protocols with associated types and generic types.

However, it seems to me like needing type erasure is often symptomatic of design problems — you're inherently "throwing away" type information (i.e. to put a value in a container or to pass it to a function), which often ultimately needs to be recovered later on anyway through verbose and brittle downcasting. Perhaps what I don't understand is the use case for a "type" like AnyHashable—PATs/protocols with self can only be used as generic constraints because they aren't reified types, which makes me wonder what compelling reasons there are to want to reify them.

In short, when is it a good idea to use type erasure in Swift? I'm looking for some general guidelines on when to use this pattern, and possibly examples of some practical use cases where type erasure is preferable to its alternatives.

Aucun commentaire:

Enregistrer un commentaire