0
0
Swiftprogramming~15 mins

Type aliases for readability in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Type aliases for readability
📖 Scenario: You are working on a simple app that tracks distances in kilometers and miles. To keep your code clear and easy to understand, you want to use type aliases to give meaningful names to the distance values.
🎯 Goal: Create type aliases for Kilometers and Miles as Double. Then use these aliases to declare variables and convert between kilometers and miles.
📋 What You'll Learn
Create a type alias called Kilometers for Double
Create a type alias called Miles for Double
Declare a variable distanceInKm of type Kilometers with value 5.0
Declare a variable distanceInMiles of type Miles and convert distanceInKm to miles using the formula miles = kilometers * 0.621371
Print the value of distanceInMiles with a descriptive message
💡 Why This Matters
🌍 Real World
Type aliases are useful in real apps to make code clearer, especially when working with units like distances, times, or currencies.
💼 Career
Understanding type aliases helps you write readable and maintainable Swift code, a skill valued in iOS and macOS development jobs.
Progress0 / 4 steps
1
Create type aliases for distances
Create a type alias called Kilometers for Double and a type alias called Miles for Double.
Swift
Need a hint?

Use the typealias keyword followed by the new name and the existing type.

2
Declare a distance variable in kilometers
Declare a variable called distanceInKm of type Kilometers and set it to 5.0.
Swift
Need a hint?

Use var distanceInKm: Kilometers = 5.0 to declare the variable.

3
Convert kilometers to miles
Declare a variable called distanceInMiles of type Miles and set it to distanceInKm multiplied by 0.621371.
Swift
Need a hint?

Multiply distanceInKm by 0.621371 and assign it to distanceInMiles.

4
Print the converted distance
Print the value of distanceInMiles with the message: "Distance in miles: " followed by the value.
Swift
Need a hint?

Use print("Distance in miles: \(distanceInMiles)") to show the result.