0
0
Swiftprogramming~30 mins

Protocol inheritance in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Protocol inheritance
📖 Scenario: Imagine you are designing a simple app to manage different types of vehicles. Some vehicles can be driven, some can fly, and some can do both. You want to organize these capabilities using Swift protocols.
🎯 Goal: You will create protocols to represent different vehicle capabilities and use protocol inheritance to combine them. Then, you will create a struct that conforms to the combined protocol and print its capabilities.
📋 What You'll Learn
Create a protocol called Drivable with a method drive() that prints "Driving on the road".
Create a protocol called Flyable with a method fly() that prints "Flying in the sky".
Create a protocol called Vehicle that inherits from both Drivable and Flyable.
Create a struct called FlyingCar that conforms to Vehicle and implements both drive() and fly() methods.
Create an instance of FlyingCar and call both drive() and fly() methods.
💡 Why This Matters
🌍 Real World
Using protocol inheritance helps organize related capabilities in apps that manage different types of objects, like vehicles with multiple functions.
💼 Career
Understanding protocol inheritance is important for Swift developers to write clean, reusable, and scalable code in iOS app development.
Progress0 / 4 steps
1
Create the base protocols
Create a protocol called Drivable with a method drive() that prints "Driving on the road". Also create a protocol called Flyable with a method fly() that prints "Flying in the sky".
Swift
Need a hint?

Protocols define methods without implementation. You will add the print statements when you implement these methods in a struct.

2
Create a protocol that inherits from both
Create a protocol called Vehicle that inherits from both Drivable and Flyable.
Swift
Need a hint?

Use a colon and list the protocols separated by commas to inherit multiple protocols.

3
Create a struct that conforms to Vehicle
Create a struct called FlyingCar that conforms to Vehicle. Implement the drive() method to print "Driving on the road" and the fly() method to print "Flying in the sky".
Swift
Need a hint?

Implement both methods inside the struct with the exact print statements.

4
Create an instance and call the methods
Create an instance of FlyingCar called myFlyingCar. Call the drive() method and then the fly() method on myFlyingCar.
Swift
Need a hint?

Remember to create the instance with let and call the methods with dot notation.