0
0
Swiftprogramming~15 mins

Protocol declaration syntax in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Protocol declaration syntax
📖 Scenario: Imagine you are creating a simple app that manages different types of vehicles. You want to make sure all vehicles can start and stop, but each vehicle might do it differently.
🎯 Goal: You will create a Vehicle protocol that requires two functions: start() and stop(). Then, you will create a struct that follows this protocol.
📋 What You'll Learn
Create a protocol named Vehicle
Add two function declarations inside the protocol: start() and stop()
Create a struct named Car that conforms to the Vehicle protocol
Implement the start() and stop() functions inside Car
Print messages when start() and stop() are called
💡 Why This Matters
🌍 Real World
Protocols are used in apps to define common behaviors for different types, like vehicles, animals, or user interface elements.
💼 Career
Understanding protocols is essential for Swift developers to write flexible and reusable code, especially in app development for iOS and macOS.
Progress0 / 4 steps
1
Create the Vehicle protocol
Write a protocol named Vehicle with two function declarations: start() and stop(). Do not add any code inside the functions.
Swift
Need a hint?

Use the protocol keyword followed by the protocol name. Inside curly braces, declare the functions without bodies.

2
Create the Car struct conforming to Vehicle
Create a struct named Car that conforms to the Vehicle protocol.
Swift
Need a hint?

Use struct Car: Vehicle to declare the struct and protocol conformance.

3
Implement start() and stop() in Car
Inside the Car struct, implement the start() function to print "Car started" and the stop() function to print "Car stopped".
Swift
Need a hint?

Use print("Car started") inside start() and print("Car stopped") inside stop().

4
Create a Car instance and call start() and stop()
Create a variable named myCar as an instance of Car. Then call myCar.start() and myCar.stop() to print the messages.
Swift
Need a hint?

Create myCar with let myCar = Car(). Then call myCar.start() and myCar.stop().