Wednesday, April 10, 2024

Run-time Polymorphism in Swift

Jordan Rose (Mastodon):

There are only three ways to get run-time polymorphism in Swift. Well, three and a half.

[…]

[…]

Generics are a powerful and flexible tool, but in general they don’t result in any more run-time polymorphism than any types (formerly “protocol composition types”). This often throws people who are used to C++ templates, where overload resolution is done on the concrete type that satisfies the generic constraints rather than on the generic type. Swift didn’t choose that option for two main reasons: it makes it much harder to diagnose issues at compile time, and it means that the entire body of the generic has to be visible to callers (so they can substitute in the concrete type). This is good for optimization, but bad for library evolution. You can think of Swift’s model as “the decision of which overload to call is made based on the knowledge where the call is written, which in this case is inside a generic function with certain constraints”.

Previously:

Comments RSS · Twitter · Mastodon

Leave a Comment