0
0
Swiftprogramming~20 mins

Protocol requirements (methods and properties) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Create myCar with Car(name: "Tesla"). Use print(myCar.name) and myCar.start() to show the output.