What if you could make different parts of your app talk the same language without rewriting code over and over?
Why Protocols in iOS Swift? - Purpose & Use Cases
Imagine you are building an app with many different types of objects, like buttons, sliders, and switches. Each object needs to respond to user taps, but you have to write separate code for each one to handle taps.
Writing separate tap-handling code for every object is slow and error-prone. If you want to add a new object type, you must remember to add tap code again. This leads to repeated code and bugs when you forget or do it inconsistently.
Protocols let you define a common set of behaviors that many different objects can share. You write the tap-handling code once in the protocol, and any object that adopts the protocol promises to implement that behavior. This keeps your code clean and consistent.
class Button { func tap() { /* handle tap */ } } class Slider { func tap() { /* handle tap differently */ } }
protocol Tappable {
func tap()
}
class Button: Tappable {
func tap() { /* handle tap */ }
}
class Slider: Tappable {
func tap() { /* handle tap differently */ }
}Protocols enable you to write flexible, reusable code that works with many object types through a shared interface.
In iOS apps, protocols let you create delegate patterns where one object tells another what happened, like a table view telling its delegate when a row is selected.
Protocols define shared behaviors for different objects.
They reduce repeated code and bugs.
They make your app easier to extend and maintain.
Practice
protocol in Swift?Solution
Step 1: Understand what a protocol defines
A protocol specifies methods and properties that a type must implement, acting as a blueprint.Step 2: Differentiate from other concepts
Protocols do not create classes or store data; they only define requirements.Final Answer:
To define a blueprint of methods and properties that a type must implement -> Option BQuick Check:
Protocol purpose = blueprint [OK]
- Confusing protocols with classes
- Thinking protocols store data
- Assuming protocols handle UI layout
Drivable in Swift?Solution
Step 1: Identify correct protocol declaration syntax
Protocols are declared with the keywordprotocolfollowed by the name and curly braces.Step 2: Check method declaration inside protocol
Methods inside protocols are declared without implementation, just the signature.Final Answer:
protocol Drivable { func drive() } -> Option DQuick Check:
Protocol syntax = keyword 'protocol' + name + method signatures [OK]
- Using class or struct instead of protocol
- Adding method implementation inside protocol
- Incorrect keyword order
protocol Greetable {
func greet() -> String
}
struct Person: Greetable {
func greet() -> String {
return "Hello!"
}
}
let p = Person()
print(p.greet())What will be printed when this code runs?
Solution
Step 1: Check protocol and struct conformance
The structPersonadoptsGreetableand implements the requiredgreet()method returning "Hello!".Step 2: Understand the print statement output
Callingp.greet()returns "Hello!", which is printed.Final Answer:
Hello! -> Option AQuick Check:
Implemented method returns "Hello!" [OK]
- Expecting protocol name printed
- Thinking missing implementation error occurs
- Assuming nil is printed
protocol Runnable {
func run()
}
struct Athlete: Runnable {
// Missing run() implementation
}Solution
Step 1: Check protocol requirements
The protocolRunnablerequires a methodrun()with no return value.Step 2: Verify struct conformance
The structAthleteadoptsRunnablebut does not implementrun(), causing a compile error.Final Answer:
Error: Athlete does not implement required method run() -> Option CQuick Check:
Missing required method causes error [OK]
- Assuming structs can't adopt protocols
- Thinking missing method is allowed
- Expecting run() to require return type
Vehicle with a property speed that can be read and set. Which of these protocol declarations is correct?Solution
Step 1: Understand property requirements in protocols
To require a property to be readable and writable, use{ get set }in the protocol.Step 2: Analyze each option
protocol Vehicle { var speed: Int { get set } } correctly declaresspeedas a variable property withget set. protocol Vehicle { var speed: Int } missesget set, so it's read-only. protocol Vehicle { func speed() -> Int } declares a method, not a property. protocol Vehicle { let speed: Int } useslet, which is not allowed in protocols.Final Answer:
protocol Vehicle { var speed: Int { get set } } -> Option AQuick Check:
Writable property = var with get set [OK]
- Using 'let' in protocol properties
- Omitting { get set } for writable properties
- Confusing methods with properties
Ready to prove it?
Pass the test and this pattern moves unknown
