0
0
Swiftprogramming~3 mins

Why Protocol requirements (methods and properties) in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could guarantee every part of your code plays by the same rules without rewriting everything?

The Scenario

Imagine you are building a game with many characters. Each character needs to move and attack, but you write separate code for each one without any shared rules.

Later, you want to add a new character, but you have to remember and rewrite all the movement and attack code again.

The Problem

Writing separate code for each character is slow and confusing. You might forget to add important actions or make mistakes because there is no clear agreement on what each character should do.

This leads to bugs and wasted time fixing repeated code.

The Solution

Protocols let you define a clear list of methods and properties that every character must have. This way, you create a simple contract that all characters follow.

Swift checks that each character implements these required methods and properties, so you never miss anything important.

Before vs After
Before
class Warrior {
  func move() { /* code */ }
  func attack() { /* code */ }
}

class Mage {
  func move() { /* code */ }
  func attack() { /* code */ }
}
After
protocol Character {
  func move()
  func attack()
}

class Warrior: Character {
  func move() { /* code */ }
  func attack() { /* code */ }
}

class Mage: Character {
  func move() { /* code */ }
  func attack() { /* code */ }
}
What It Enables

Protocols make your code organized and safe by ensuring all types follow the same rules, making it easier to add new features and fix bugs.

Real Life Example

Think of a remote control that works with many devices. The remote expects every device to respond to certain buttons like power and volume. Protocols are like that remote's instructions, making sure every device knows how to respond.

Key Takeaways

Protocols define required methods and properties as a contract.

They prevent mistakes by enforcing consistent implementation.

Protocols make adding new types easier and safer.