0
0
Swiftprogramming~20 mins

Type casting with as, as?, as! in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Casting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code using 'as?'?

Consider the following Swift code snippet. What will be printed?

Swift
class Animal {}
class Dog: Animal {}

let animal: Animal = Dog()
if let dog = animal as? Dog {
    print("Dog cast succeeded")
} else {
    print("Dog cast failed")
}
ADog cast succeeded
BDog cast failed
CCompile-time error
DRuntime crash
Attempts:
2 left
💡 Hint

Remember that 'as?' tries to cast safely and returns nil if it fails.

Predict Output
intermediate
2:00remaining
What happens when using 'as!' to cast an incompatible type?

What is the result of running this Swift code?

Swift
class Animal {}
class Cat: Animal {}
class Dog: Animal {}

let animal: Animal = Cat()
let dog = animal as! Dog
print("Cast succeeded")
ARuntime crash with a fatal error
BPrints "Cast succeeded"
CCompile-time error
DPrints nothing
Attempts:
2 left
💡 Hint

Think about what happens when you force cast to a wrong type.

🧠 Conceptual
advanced
1:30remaining
Which statement about 'as' casting is true?

Choose the correct statement about the as keyword in Swift.

A<code>as</code> can only be used to cast between unrelated types.
B<code>as</code> always performs a runtime check and returns an optional.
C<code>as</code> is used for upcasting and bridging between types without runtime checks.
D<code>as</code> is used to force cast and crashes if the cast fails.
Attempts:
2 left
💡 Hint

Think about when as can be used without optional or force casting.

Predict Output
advanced
2:00remaining
What is the output of this code using 'as?' with an array?

What will this Swift code print?

Swift
let mixedArray: [Any] = ["Hello", 42, 3.14]
if let stringArray = mixedArray as? [String] {
    print("String array: \(stringArray)")
} else {
    print("Cast to [String] failed")
}
AString array: ["Hello", "42", "3.14"]
BCast to [String] failed
CCompile-time error
DString array: ["Hello"]
Attempts:
2 left
💡 Hint

Remember that as? requires all elements to be of the target type.

🔧 Debug
expert
2:30remaining
Why does this forced cast crash at runtime?

Examine the code below. Why does it crash at runtime?

Swift
class Vehicle {}
class Car: Vehicle {}
class Bike: Vehicle {}

let vehicle: Vehicle = Vehicle()
let car = vehicle as! Car
print("Car cast succeeded")
ABecause <code>Car</code> is not a subclass of <code>Vehicle</code>.
BBecause <code>as!</code> cannot be used with classes.
CBecause <code>vehicle</code> is nil and cannot be cast.
DBecause <code>vehicle</code> is not an instance of <code>Car</code>, so forced cast fails.
Attempts:
2 left
💡 Hint

Check the actual type of the instance stored in vehicle.