ArchitectureMidMCQ

What is the difference between composition and inheritance?

Test your knowledge:

Explanation & Code

Answer:

  • Inheritance — a class derives behaviour from a parent class ("is-a" relationship)
  • Composition — a type gets behaviour by holding references to other objects ("has-a" relationship)

Swift favours composition through protocols and protocol extensions.

Code Example:

// ❌ Inheritance — rigid, can't mix and match
class Animal {
    func breathe() { }
}
class Dog: Animal {
    func bark() { }
}
class FlyingDog: Dog { }  // gets everything even if unneeded

// ✅ Composition — flexible, modular
protocol Breathable { func breathe() }
protocol Swimmable { func swim() }
protocol Flyable { func fly() }

struct Duck: Breathable, Swimmable, Flyable {
    func breathe() { }
    func swim() { }
    func fly() { }
}

// Protocol extensions provide default implementations
extension Swimmable {
    func swim() { print("Splashing...") }
}

Rate your understanding:

Ready to practice more Architecture?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.