Browse Questions
  • These determine how ARC (Automatic Reference Counting) manages object lifetimes.
  • Polymorphism lets code work with values of different underlying types through a single shared interface.
  • UIViewPropertyAnimator is an object that owns an animation, which makes that animation interruptible, reversible, and scrubbable.
  • ARC is Swift's compile-time memory management system that automatically inserts retain and release calls to allocate and free class instances on the heap.

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 }