0
0
Swiftprogramming~15 mins

Typealias for custom naming in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Typealias for custom naming
📖 Scenario: Imagine you are creating a simple app that tracks distances in kilometers. You want to make your code easier to read by giving a custom name to the Double type that represents distances.
🎯 Goal: You will create a typealias called Distance for Double, then use it to declare variables and print their values.
📋 What You'll Learn
Create a typealias named Distance for the Double type
Declare a variable called homeToSchool of type Distance with the value 3.5
Declare a variable called schoolToPark of type Distance with the value 1.2
Calculate the total distance by adding homeToSchool and schoolToPark
Print the total distance using print
💡 Why This Matters
🌍 Real World
Using <code>typealias</code> helps make code easier to read and understand by giving meaningful names to types, especially in apps dealing with measurements or complex data.
💼 Career
Many software jobs require writing clear and maintainable code. Knowing how to use <code>typealias</code> is a simple way to improve code clarity and teamwork.
Progress0 / 4 steps
1
Create a typealias for Distance
Write typealias Distance = Double to create a new name Distance for the type Double.
Swift
Need a hint?

Use the typealias keyword followed by the new name, an equals sign, and the existing type.

2
Declare distance variables using Distance
Declare a variable called homeToSchool of type Distance and set it to 3.5. Then declare a variable called schoolToPark of type Distance and set it to 1.2.
Swift
Need a hint?

Use var keyword, variable name, colon, type Distance, equals sign, and the value.

3
Calculate total distance
Create a variable called totalDistance of type Distance and set it to the sum of homeToSchool and schoolToPark.
Swift
Need a hint?

Add the two variables and assign the result to totalDistance with type Distance.

4
Print the total distance
Write print(totalDistance) to display the total distance on the screen.
Swift
Need a hint?

Use the print function with totalDistance inside the parentheses.