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?
✗ 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?✗ 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?
✗ 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?
✗ Incorrect
as? returns an optional and lets you handle failure safely.What type does
as? return when casting?✗ 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.