Bird
0
0

Which code snippet correctly prepares data before transitioning to a new view controller using a segue in Swift?

easy📝 Conceptual Q2 of 15
iOS Swift - Navigation
Which code snippet correctly prepares data before transitioning to a new view controller using a segue in Swift?
Aoverride func viewDidLoad() { let dest = NextViewController() dest.data = "Hello" }
Boverride func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "nextScreen" { let dest = segue.destination as? NextViewController dest?.data = "Hello" } }
Coverride func prepare(for segue: UIStoryboardSegue, sender: Any?) { let dest = NextViewController() dest.data = "Hello" }
Doverride func prepare(for segue: UIStoryboardSegue, sender: Any?) { segue.destination.data = "Hello" }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct method

    Data should be set inside prepare(for:sender:) before segue.
  2. Step 2: Proper casting

    Cast segue.destination to the correct VC type using optional binding.
  3. Step 3: Assign data

    Assign the data property safely to avoid crashes.
  4. Final Answer:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "nextScreen" { let dest = segue.destination as? NextViewController dest?.data = "Hello" } } correctly uses prepare(for:sender:), checks identifier, casts, and assigns data.
  5. Quick Check:

    prepare + cast + assign = correct [OK]
Quick Trick: Use prepare(for:sender:) with safe casting [OK]
Common Mistakes:
  • Creating a new instance instead of using segue.destination
  • Not checking segue identifier
  • Forgetting to cast destination VC

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes