0
0
Swiftprogramming~5 mins

Type casting with as, as?, as! in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
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
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
Which type casting keyword is used for guaranteed upcasting in Swift?
Aas
Bas!
Cas?
Dcast
If you want to safely check if a cast is possible and handle failure, which keyword should you use?
Aas?
Bas!
Ctry
Das
What type does as? return when casting?
ANon-optional type
BOptional type
CForced unwrapped type
DVoid
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.