0
0
Swiftprogramming~30 mins

Adding methods in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Adding methods
📖 Scenario: You are creating a simple program to manage a car's information and actions.
🎯 Goal: Build a Swift program that defines a Car struct with properties and adds methods to display details and update the car's mileage.
📋 What You'll Learn
Create a struct named Car with properties make, model, and mileage
Add a method displayDetails() that prints the car's make, model, and mileage
Add a method drive(distance: Int) that increases the mileage by the given distance
Create an instance of Car with specific values
Call the methods to show the car details and update mileage
💡 Why This Matters
🌍 Real World
Managing objects like cars with properties and actions is common in apps for car rentals, maintenance tracking, or sales.
💼 Career
Understanding how to add methods to data structures is essential for building interactive and functional software in Swift development.
Progress0 / 4 steps
1
Create the Car struct with properties
Create a struct called Car with three properties: make and model of type String, and mileage of type Int. Then create a variable myCar of type Car with make set to "Toyota", model set to "Corolla", and mileage set to 50000.
Swift
Need a hint?

Use struct Car { ... } to define the structure. Add properties inside with var. Create myCar using the struct's initializer.

2
Add the displayDetails() method
Inside the Car struct, add a method called displayDetails() that prints the car's make, model, and mileage in this format: "Car: Toyota Corolla, Mileage: 50000".
Swift
Need a hint?

Define a func displayDetails() inside Car. Use print with string interpolation to show the details.

3
Add the drive(distance:) method
Inside the Car struct, add a method called drive(distance: Int) that increases the mileage property by the given distance. Remember to mark the method as mutating because it changes the struct's property.
Swift
Need a hint?

Use mutating func drive(distance: Int) to change mileage. Add the distance to mileage inside the method.

4
Use the methods and print the output
Call myCar.displayDetails() to print the initial details. Then call myCar.drive(distance: 150) to add 150 to the mileage. Finally, call myCar.displayDetails() again to print the updated details.
Swift
Need a hint?

Call displayDetails() before and after calling drive(distance: 150) on myCar.