DevPrep

All topics › Object-oriented programming (OOP)

Polymorphism

Junior

Essence

Polymorphism is the ability to work with different types through one interface: one call, different implementations. "One interface, many implementations." Swift has four practically important kinds.

Kinds in Swift

// 1. Subtype polymorphism: class hierarchy, vtable dispatch
class Animal { func sound() -> String { "..." } }
class Dog: Animal { override func sound() -> String { "Woof" } }

// 2. Protocol polymorphism: witness table (existential `any`)
protocol Drawable { func draw() -> String }
struct Square: Drawable { func draw() -> String { "□" } }
struct Dot: Drawable { func draw() -> String { "•" } }
let items: [any Drawable] = [Square(), Dot()]
print(items.map { $0.draw() }.joined())   // □•

// 3. Parametric polymorphism: generics, static dispatch + specialization
func largest<T: Comparable>(_ values: [T]) -> T? { values.max() }
print(largest([3, 9, 2]) ?? 0)   // 9
print(largest(["b", "a"]) ?? "") // b

// 4. Ad hoc polymorphism: overloading
func describe(_ x: Int) -> String { "int \(x)" }
func describe(_ x: String) -> String { "string \(x)" }
print(describe(1), describe("a"))   // int 1 string a

What the interviewer looks for

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store