Consider the following Swift code snippet. What will be printed?
class Animal {} class Dog: Animal {} let animal: Animal = Dog() if let dog = animal as? Dog { print("Dog cast succeeded") } else { print("Dog cast failed") }
Remember that 'as?' tries to cast safely and returns nil if it fails.
The variable animal actually holds a Dog instance. Using as? safely casts it to Dog, so the cast succeeds and prints "Dog cast succeeded".
What is the result of running this Swift code?
class Animal {} class Cat: Animal {} class Dog: Animal {} let animal: Animal = Cat() let dog = animal as! Dog print("Cast succeeded")
Think about what happens when you force cast to a wrong type.
The variable animal holds a Cat instance. Forcing a cast to Dog with as! causes a runtime crash because the types are incompatible.
Choose the correct statement about the as keyword in Swift.
Think about when as can be used without optional or force casting.
as is used for upcasting (casting to a superclass or protocol) or bridging (e.g., between Swift and Objective-C types) and does not perform runtime checks. It never returns an optional or crashes.
What will this Swift code print?
let mixedArray: [Any] = ["Hello", 42, 3.14] if let stringArray = mixedArray as? [String] { print("String array: \(stringArray)") } else { print("Cast to [String] failed") }
Remember that as? requires all elements to be of the target type.
The array contains different types: String, Int, and Double. Casting the whole array to [String] fails because not all elements are strings, so the else branch runs.
Examine the code below. Why does it crash at runtime?
class Vehicle {} class Car: Vehicle {} class Bike: Vehicle {} let vehicle: Vehicle = Vehicle() let car = vehicle as! Car print("Car cast succeeded")
Check the actual type of the instance stored in vehicle.
The variable vehicle holds an instance of Vehicle itself, not a subclass Car. Forced casting to Car fails at runtime causing a crash.