Protocols vs abstract classes

Swift language Junior Swift 5.7+ iOS 17+ Reviewed By Alok Singh

Pick the fix

Structs and classes both need a describe() method with a shared default. Which approach?

Options
Hint 1 of 1

Which option works for structs?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A A protocol with describe() as a requirement plus a default in a protocol extension

Correct. Any type can conform and override.

Why not the others?
  • B A base class with describe() that calls fatalError unless overridden. Structs can't inherit, and mistakes only show at runtime.
  • C Copy the method into each type. Duplication, with no shared contract.
  • D An @objc protocol with an optional requirement. @objc protocols work only with classes.

30-second answer

A protocol defines requirements that any type (struct, enum, class or actor) can adopt, and protocol extensions add default implementations. Swift has no abstract classes; a base class with methods that crash if not overridden is the usual imitation. Protocols allow multiple conformances and work with value types, which is why Swift is called protocol-oriented.

Practise saying it · 30 s. No recording, just a timer

Compare protocols and abstract classes.

Say your answer out loud, then check which of these points you covered:

  • Any type can conform
  • Defaults via extensions
  • No abstract classes in Swift

Deep dive

Default implementations in extensions are statically dispatched unless the method is also a requirement.

Use primary associated types (protocol Store<Item>) for clean generic constraints.

Classes are still useful when you need shared stored state or inheritance from UIKit.

Protocol composition: Codable & Sendable.

Common mistakes

  • Adding a method only in an extension and expecting overrides to be called through the protocol.
  • Recreating abstract classes with fatalError.

Senior take & follow-ups

Seniors explain static versus dynamic dispatch in protocol extensions.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why can an extension method 'not be overridden'?

    Show hint

    Only requirements are dynamically dispatched.

  2. Can protocols have stored properties?

    Show hint

    No; they declare requirements, and conformers provide the storage.

Suggest a fix if something here is wrong or out of date.