What does the as keyword do in Swift type casting?
The <code>as</code> keyword is used for upcasting or type conversion that is guaranteed to succeed. It converts an instance to a superclass or protocol type without risk of failure.
Click to reveal answer
intermediate
What is the difference between as? and as! in Swift?
as? is a conditional cast that returns an optional value and safely fails if the cast is not possible. as! is a forced cast that assumes the cast will succeed and crashes if it fails.
Click to reveal answer
beginner
When should you use as? instead of as!?
Use as? when you are not sure if the cast will succeed and want to safely handle failure without crashing your program.
Click to reveal answer
beginner
What happens if you use as! to cast to an incompatible type?
The program will crash at runtime with a fatal error because as! forces the cast and does not check if it is valid.
Click to reveal answer
intermediate
Explain upcasting and downcasting with as and as? in Swift.
Upcasting (using <code>as</code>) converts a subclass instance to a superclass type and always succeeds. Downcasting (using <code>as?</code> or <code>as!</code>) tries to convert a superclass instance to a subclass type and may fail, so <code>as?</code> returns an optional and <code>as!</code> forces the cast.
Click to reveal answer
Which keyword in Swift safely tries to cast a value and returns nil if it fails?
Aas!
Bas
Cas?
Dcast
✗ Incorrect
as? is the conditional cast that returns an optional and safely fails if the cast is not possible.
What will happen if you use as! to cast to an incompatible type?
AThe compiler shows an error
BThe cast returns nil
CThe cast silently fails and continues
DThe program crashes with a runtime error
✗ Incorrect
as! forces the cast and crashes the program if the cast is invalid.
Which type casting keyword is used for guaranteed upcasting in Swift?
Aas
Bas!
Cas?
Dcast
✗ Incorrect
as is used for upcasting and always succeeds.
If you want to safely check if a cast is possible and handle failure, which keyword should you use?
Aas?
Bas!
Ctry
Das
✗ Incorrect
as? returns an optional and lets you handle failure safely.
What type does as? return when casting?
ANon-optional type
BOptional type
CForced unwrapped type
DVoid
✗ Incorrect
as? returns an optional type because the cast might fail.
Explain the differences between as, as?, and as! in Swift type casting.
Think about safety and when the cast might fail.
You got /3 concepts.
Describe a real-life situation where you would use as? instead of as!.
Imagine you are not sure about the type of an object.
You got /3 concepts.
Practice
(1/5)
1. Which of the following statements correctly describes the use of as? in Swift?
easy
A. as? is used only for upcasting and always succeeds.
B. as? attempts a cast and returns an optional value.
C. as? forcefully casts and crashes if it fails.
D. as? converts any type to a string.
Solution
Step 1: Understand as? behavior
as? tries to cast a value to a different type and returns an optional, which is nil if the cast fails.
Step 2: Compare with other casting operators
as! force casts and crashes if it fails, while as is for guaranteed casts like upcasting.
Final Answer:
as? attempts a cast and returns an optional value. -> Option B
2. Which of the following is the correct syntax to force cast a variable value to type String?
easy
A. let str = value as! String
B. let str = value as String!
C. let str = value as String?
D. let str = value as? String
Solution
Step 1: Identify force cast syntax
Force casting uses as! to convert a value to a type, crashing if it fails.
Step 2: Check each option
let str = value as! String uses as! correctly. let str = value as? String is safe cast, B and C are invalid syntax.
Final Answer:
let str = value as! String -> Option A
Quick Check:
Force cast = as! [OK]
Hint: Force cast uses as! with exclamation mark [OK]
Common Mistakes:
Using as? when force cast is needed
Writing invalid syntax like as String!
Confusing optional cast with force cast
3. What will be the output of the following Swift code?
class Animal {}
class Dog: Animal {}
let animal: Animal = Dog()
if let dog = animal as? Dog {
print("It's a dog")
} else {
print("Not a dog")
}
medium
A. It's a dog
B. Not a dog
C. Compile-time error
D. Runtime crash
Solution
Step 1: Understand the class hierarchy and casting
Dog is a subclass of Animal. The variable animal holds a Dog instance but typed as Animal.
Step 2: Use safe cast as? to check type
The if let safely casts animal to Dog. Since animal is actually a Dog, cast succeeds.
Final Answer:
It's a dog -> Option A
Quick Check:
Safe cast success prints "It's a dog" [OK]
Hint: Safe cast with as? returns non-nil if type matches [OK]
Common Mistakes:
Assuming cast fails because variable type is superclass
Confusing as with as?
Expecting runtime crash without force cast
4. Consider this Swift code snippet:
let value: Any = "Hello"
let number = value as! Int
print(number)
What is the issue with this code?
medium
A. It will print "Hello" as an Int.
B. It will safely return nil.
C. It will compile but print 0.
D. It will cause a runtime crash due to invalid force cast.
Solution
Step 1: Analyze the force cast operation
The variable value holds a String "Hello" but is force cast to Int using as!.
Step 2: Understand force cast failure
Since "Hello" cannot be cast to Int, the force cast crashes at runtime.
Final Answer:
It will cause a runtime crash due to invalid force cast. -> Option D
Quick Check:
Force cast invalid type = crash [OK]
Hint: Force cast wrong type crashes at runtime [OK]
Common Mistakes:
Expecting print output instead of crash
Thinking force cast returns nil on failure
Confusing as! with safe cast as?
5. You have an array of Any containing mixed types: ["Swift", 42, 3.14, "Code"]. You want to create a new array containing only the strings by safely casting each element. Which code snippet correctly does this using as??
hard
A. let strings = mixedArray.filter { $0 as? String != nil }
B. let strings = mixedArray.map { $0 as! String }
C. let strings = mixedArray.compactMap { $0 as? String }
D. let strings = mixedArray.map { $0 as? String }
Solution
Step 1: Understand the goal and methods
We want only strings from a mixed array, safely casting each element.
Step 2: Analyze each option
let strings = mixedArray.compactMap { $0 as? String } uses compactMap with safe cast as?, which filters out nils and unwraps strings correctly. let strings = mixedArray.map { $0 as! String } force casts and may crash. let strings = mixedArray.filter { $0 as? String != nil } filters but keeps original types, not strings. let strings = mixedArray.map { $0 as? String } maps to optionals, resulting in array of optionals, not strings.
Final Answer:
let strings = mixedArray.compactMap { $0 as? String } -> Option C
Quick Check:
Safe cast + compactMap filters and unwraps [OK]
Hint: Use compactMap with as? to filter and unwrap safely [OK]
Common Mistakes:
Using map with force cast causing crashes
Using filter without unwrapping optionals
Expecting map with as? to unwrap optionals
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.