Protocol requirements (methods and properties) in Swift
📖 Scenario: You are creating a simple app to manage different types of vehicles. Each vehicle must have a name and a way to start it. You will use a protocol to define these requirements.
🎯 Goal: Build a Swift program that defines a protocol with method and property requirements, then create a struct that conforms to this protocol and implements the required method and property.
📋 What You'll Learn
Define a protocol called Vehicle with a read-only property name of type String
Add a method requirement start() in the Vehicle protocol
Create a struct called Car that conforms to the Vehicle protocol
Implement the name property and start() method in the Car struct
Print the car's name and call the start() method to show the output
💡 Why This Matters
🌍 Real World
Protocols are used in Swift to define common behavior that different types can share, such as vehicles having names and start methods.
💼 Career
Understanding protocols is essential for Swift developers to write flexible, reusable, and maintainable code in apps and frameworks.
Progress0 / 4 steps
1
Define the Vehicle protocol
Define a protocol called Vehicle with a read-only property name of type String and a method requirement start().
Swift
Hint
Use protocol keyword. The property name should be read-only, so use { get }. The method start() has no parameters and no return value.
2
Create the Car struct conforming to Vehicle
Create a struct called Car that conforms to the Vehicle protocol. Add a stored property name of type String.
Swift
Hint
Use struct Car: Vehicle to conform. The name property can be a constant let. Implement the start() method inside the struct.
3
Implement the start() method
Inside the Car struct, implement the start() method to print the message: " is starting" where is the car's name.
Swift
Hint
Use print with string interpolation to include the name property in the message.
4
Create a Car instance and call start()
Create a constant myCar of type Car with the name "Tesla". Then print myCar.name and call myCar.start().
Swift
Hint
Create myCar with Car(name: "Tesla"). Use print(myCar.name) and myCar.start() to show the output.
Practice
(1/5)
1. What does a protocol in Swift require from a type that adopts it?
easy
A. To declare new methods unrelated to the protocol
B. To inherit from a superclass
C. To override all existing methods
D. To implement all the methods and properties declared in the protocol
Solution
Step 1: Understand protocol purpose
Protocols define a set of methods and properties that a type must implement.
Step 2: Check adoption requirements
Any type adopting a protocol must provide implementations for all its requirements.
Final Answer:
To implement all the methods and properties declared in the protocol -> Option D
Quick Check:
Protocol adoption = implement all requirements [OK]
Hint: Protocols require full implementation of declared methods and properties [OK]
Common Mistakes:
Thinking protocols require inheritance from a class
Assuming methods can be skipped
Confusing protocol adoption with subclassing
2. Which of the following is the correct way to declare a read-only property requirement in a Swift protocol?
easy
A. var name: String { get }
B. var name: String { get set }
C. let name: String
D. func name() -> String
Solution
Step 1: Recall property syntax in protocols
Read-only properties use { get } to indicate they must be readable but not necessarily writable.
Step 2: Analyze options
var name: String { get } uses { get } correctly; var name: String { get set } requires read-write; let name: String is invalid in protocols; func name() -> String is a method, not a property.
Final Answer:
var name: String { get } -> Option A
Quick Check:
Read-only property = { get } [OK]
Hint: Use { get } for read-only property in protocols [OK]
Common Mistakes:
Using let instead of var in protocol
Confusing methods with properties
Using { get set } for read-only properties
3. Consider the following Swift code:
protocol Vehicle {
var speed: Double { get set }
func description() -> String
}
struct Car: Vehicle {
var speed: Double
func description() -> String {
return "Car speed is \(speed) km/h"
}
}
let myCar = Car(speed: 80)
print(myCar.description())
What is the output when this code runs?
medium
A. Error: Protocol requirements not met
B. Car speed is 80.0 km/h
C. Car speed is 80 km/h
D. Car speed is km/h
Solution
Step 1: Check protocol conformance
Car struct implements the required property speed and method description(), fulfilling Vehicle protocol.
Step 2: Analyze print output
The description() returns "Car speed is \(speed) km/h". Since speed is 80.0 (Double), string interpolation formats it as "80.0".
Hint: String interpolation for Double 80.0 prints '80.0' [OK]
Common Mistakes:
Expecting 80 instead of 80.0
Thinking protocol conformance causes error
Missing string interpolation syntax
4. Given this protocol and struct:
protocol Shape {
var area: Double { get }
func perimeter() -> Double
}
struct Square: Shape {
var side: Double
var area: Double {
side * side
}
}
What is the error in the code?
medium
A. area property should be var with get set
B. side property must be a constant (let)
C. Missing implementation of perimeter() method
D. Square cannot have computed properties
Solution
Step 1: Check protocol requirements
Shape protocol requires a read-only property area and a method perimeter().
Step 2: Verify Square struct implementation
Square implements area as computed property but does not implement perimeter() method.
Final Answer:
Missing implementation of perimeter() method -> Option C
Quick Check:
All protocol methods must be implemented [OK]
Hint: All protocol methods must be implemented, or error occurs [OK]
Common Mistakes:
Assuming computed properties are not allowed
Thinking get set is required for read-only
Ignoring missing method implementations
5. You want to create a protocol Identifiable that requires a read-only id property of type String and a method identify() that prints the id. Which of the following is the correct protocol and extension to provide a default implementation of identify()?
hard
A. protocol Identifiable {
var id: String { get }
func identify()
}
extension Identifiable {
func identify() {
print("ID: \(id)")
}
}
B. protocol Identifiable {
var id: String { get set }
func identify()
}
extension Identifiable {
func identify() {
print(id)
}
}
C. protocol Identifiable {
let id: String
func identify()
}
extension Identifiable {
func identify() {
print("ID is " + id)
}
}
D. protocol Identifiable {
var id: String { get }
func identify() -> String
}
extension Identifiable {
func identify() -> String {
return id
}
}
Solution
Step 1: Define protocol requirements
id must be read-only, so use { get } and identify() method with no return.
Step 2: Provide default implementation in extension