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 BicycleCreate a Boolean variable called
useSafeCasting set to trueUse 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 castingPrint 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