0
0
Swiftprogramming~30 mins

Type casting with as, as?, as! in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Type Casting with as, as?, as! in Swift
📖 Scenario: Imagine you are building a simple app that manages a list of different types of vehicles. Each vehicle can be a Car or a Bicycle. You want to check the type of each vehicle and print specific details.
🎯 Goal: You will create a list of vehicles, add a configuration variable to control safe casting, use type casting with as, as?, and as! to identify vehicle types, and finally print the details.
📋 What You'll Learn
Create a list called vehicles containing exactly two objects: a Car and a Bicycle
Create a Boolean variable called useSafeCasting set to true
Use a for loop with variables vehicle to iterate over vehicles and use as? for safe casting when useSafeCasting is true, otherwise use as! for forced casting
Print the type and details of each vehicle using print()
💡 Why This Matters
🌍 Real World
Type casting is useful when you have a list of mixed objects and need to work with their specific types safely or forcefully.
💼 Career
Understanding type casting helps in writing safer and more flexible Swift code, especially when working with collections of different object types in apps.
Progress0 / 4 steps
1
Create the vehicle classes and the vehicles list
Create a class called Car with a property model set to "Sedan" and a class called Bicycle with a property type set to "Mountain". Then create a list called vehicles containing one Car() and one Bicycle().
Swift
Need a hint?

Define two simple classes with one property each. Then create a list called vehicles that holds one instance of each class.

2
Add a configuration variable for safe casting
Create a Boolean variable called useSafeCasting and set it to true.
Swift
Need a hint?

Just create a Boolean variable named useSafeCasting and set it to true.

3
Use type casting with as?, as! inside a loop
Use a for loop with variable vehicle to iterate over vehicles. Inside the loop, if useSafeCasting is true, use as? to safely cast vehicle to Car or Bicycle. If useSafeCasting is false, use forced casting as! instead.
Swift
Need a hint?

Use a for loop to check each vehicle. Use as? for safe casting when useSafeCasting is true, otherwise use as! for forced casting. Use if let to unwrap safely.

4
Print the vehicle details
Print the type and details of each vehicle inside the loop using print(). For example, print "Safe cast: Car model is Sedan" or "Safe cast: Bicycle type is Mountain" depending on the cast.
Swift
Need a hint?

Use print() inside the loop to show the vehicle type and its property value after casting.