Polymorphism in swift

Hello there, im trying to refresh my knowledge on basics and cofronted the problem.
I dont completely understand how polymorphism works in swift.
I understood the idea of the expample provided in the net:
class Person {}
class Manager : Person {}
class Driver : Person {}

and every class has a method , overriden in subclasses, so when we call for it , it does different things depending on type of the object using it.

So my question is : can someone maybe explain how polymorphism is implemented in swift?
what mechanism makes polymorphism work is swift ?

Or maybe someone could tell me why exactly generics are good exaplmes of polymorphism paradigm?

Run-time polymorphism is implemented exactly as you indicated in your post. Classes are the only structure in Swift that implements a super-class -> sub-class relationship. Structs and enums don't.

Generics provide a means of implementing "compile-time" polymorphism, if you will. The generic construct (function, class, struct, enum) represents a template that the compiler fills out for each new type that instantiates the generic construct and creates a new code instance based on the filled out template.

1 Like

This isn't totally true, as discussed in this often-linked talk by @Slava_Pestov and @John_McCall. Swift does support monomorphization, where each concrete type the function is called with results in different code synthesis, but also can emit generic functions such that the proper implementations for each type can be accessed dynamically through a witness table.

4 Likes

That may be true, but the programmer's model, at least in my head, is what I described. Using a witness table under certain circumstances is a compiler implementation detail.

There are combinations of features that can't be understood purely using a static-monomorphization model. For example, Swift allows you to override generic methods in subclasses.

9 Likes

I understand, however, the original OP was asking about what "polymorphism" is, both run-time and compile-time. The nuances of how the features of generics combine together still requires a fundamental understanding of that concept. I've been using generics since Ada in the '80s, but, it took awhile to really grasp the concept, and everything Swift has as part of the generics support can be hard to grapple with if you don't have some understanding or model of what is trying to be accomplished.