OOPMidMCQ
What is polymorphism, and what forms does it take in Swift?
Test your knowledge:
Explanation & Code
Answer: Polymorphism lets code work with values of different underlying types through a single shared interface. Swift supports several flavors:
- Subtype (runtime) polymorphism — a subclass overrides a base class's method, and the override is dispatched at runtime via
dynamic/vtable dispatch. - Protocol (ad-hoc) polymorphism — unrelated types conform to the same protocol and are used interchangeably, often via existentials (
any Protocol) or generics. - Parametric (generic) polymorphism — a single function/type works across many types via generics, resolved at compile time.
- Ad-hoc polymorphism (overloading) — the same function name behaves differently based on argument types.
// Subtype polymorphism
class Shape { func area() -> Double { 0 } }
class Circle: Shape {
let radius: Double
init(radius: Double) { self.radius = radius }
override func area() -> Double { .pi * radius * radius }
}
// Protocol polymorphism
protocol Drawable { func draw() }
struct Square: Drawable { func draw() { /* ... */ } }
struct Triangle: Drawable { func draw() { /* ... */ } }
let shapes: [any Drawable] = [Square(), Triangle()]
// Parametric (generic) polymorphism
func firstElement<T>(of array: [T]) -> T? { array.first }
Rate your understanding: