Skip to content
Prepare to Grow

Swift Fundamentals

Polymorphism and Type Casting

Work safely with superclass references, overridden behavior, runtime type checks, and conditional casts.

Beginner5 min read2 guided activities

Before you begin

What you will understand

  • Explain runtime polymorphism.
  • Use superclass references with subclass instances.
  • Check types with is and cast safely with as?.
  • Recognize the risk of forced casts.
01

Learning stage

Concept Explanation

Polymorphism lets code work through a shared superclass or protocol while each concrete value provides its own behavior. When an overridden method is called through a superclass reference, Swift dispatches to the runtime instance's implementation.

Type casting inspects or refines runtime type information. is checks whether a value has a type, as performs a cast known to succeed, as? produces an optional for a conditional cast, and as! traps if the forced cast fails.

  • Superclass references can hold subclass instances.
  • Overridden methods dispatch according to runtime type.
  • is performs a runtime type check.
  • as? is the safe default for uncertain downcasts.
02

Learning stage

Syntax & Examples

A mixed superclass collection uses polymorphic summaries and conditionally accesses video-specific data.

PolymorphicLessons.swiftswift
class LessonItem {
  let title: String
  init(title: String) { self.title = title }
  func summary() -> String { title }
}

final class VideoItem: LessonItem {
  let duration: Int
  init(title: String, duration: Int) {
      self.duration = duration
      super.init(title: title)
  }
  override func summary() -> String { "Video: \(title)" }
}

let items: [LessonItem] = [
  LessonItem(title: "Swift Basics"),
  VideoItem(title: "Polymorphism", duration: 14)
]

for item in items {
  print(item.summary())
  if let video = item as? VideoItem {
      print("Duration: \(video.duration) min")
  }
}
Each summary uses the runtime implementation; only the video successfully downcasts.
03

Learning stage

Real-World Usage

These concepts appear throughout production iOS code. Focus on the requirement each technique communicates.

  • UIKit APIs often return or store superclass references whose runtime instances are specialized subclasses.
  • Polymorphic collections can coordinate several implementations through one shared contract.
  • Conditional casts are useful at framework boundaries where runtime types are not fully known.
04

Learning stage

Common Mistakes

Notice these mistakes early so the compiler and type system can help instead of becoming obstacles.

  • Using as! for a cast that can legitimately fail.
  • Casting repeatedly instead of designing a shared protocol or superclass capability.
  • Confusing a declared variable type with the instance's runtime type.
  • Building behavior from long chains of type checks instead of polymorphic methods.
05

Learning stage

Practice Exercises

Work through these activities in a small Xcode project. No embedded playground is required on this site.

Activity 1

Build a polymorphic collection

Create ArticleItem and VideoItem subclasses, store both as LessonItem values, and call an overridden summary on each.

Hint: The array's element type can be the common superclass.

Activity 2

Downcast safely

Use as? to access one property that exists only on VideoItem and handle the non-video case without force casting.

Hint: Optional binding combines the cast check and unwrapping.

06

Learning stage

Knowledge Check

Answer each question before revealing the explanation.

QUESTION 1

What does an unsuccessful as? cast return?

  1. A.nil
  2. B.false
  3. C.The original object
  4. D.A runtime crash
Reveal answer

nil

A conditional cast produces an optional of the requested type.

QUESTION 2

Which implementation runs when an overridden method is called through a superclass reference?

Reveal answer

The implementation belonging to the instance's runtime type.

07

Learning stage

Interview Preparation

Explain the idea in terms of its purpose, behavior, and tradeoffs rather than reciting syntax.

What is polymorphism in Swift?

Short answer: It lets code use a shared type while runtime instances provide specialized behavior.

Explore the detailed answer

A superclass or protocol reference defines the operations callers can use. Concrete subclasses or conforming types implement those operations, and dispatch selects the appropriate implementation. This reduces caller knowledge of concrete types and enables substitution.

Possible follow-ups

  • • How do as? and as! differ?
  • • When is type checking a design smell?
08

Learning stage

Key Takeaways

Polymorphism lets callers depend on shared behavior while concrete types remain specialized. Cast only at boundaries where more specific runtime knowledge is genuinely required.

  • Declared and runtime types can differ.
  • Overrides enable runtime polymorphism.
  • is checks and as? conditionally casts.
  • Forced casts can crash and should be rare.