Bird
0
0

What is the error in the following code that causes a crash when performing the segue?

medium📝 Debug Q14 of 15
iOS Swift - Navigation
What is the error in the following code that causes a crash when performing the segue?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  let destinationVC = segue.destination as! DetailViewController
  destinationVC.data = "Hello"
}
AAssigning data after the segue completes
BUsing forced cast instead of optional cast
CMissing check for segue.identifier before casting
DNot calling super.prepare(for:sender:)
Step-by-Step Solution
Solution:
  1. Step 1: Identify missing segue identifier check

    The code casts destinationVC without checking if the segue.identifier matches the expected one, risking wrong destination type.
  2. Step 2: Understand crash cause

    If the segue is not to DetailViewController, forced cast fails and crashes the app.
  3. Final Answer:

    Missing check for segue.identifier before casting -> Option C
  4. Quick Check:

    Always check segue.identifier before casting [OK]
Quick Trick: Always check segue.identifier before casting destination [OK]
Common Mistakes:
  • Skipping identifier check causes crash
  • Assuming forced cast is always safe
  • Ignoring optional cast or guard statements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes