Bird
0
0

Why does this code cause a crash? let newVC: UIViewController? = nil navigationController?.pushViewController(newVC!, animated: true)

medium📝 Debug Q7 of 15
iOS Swift - Navigation
Why does this code cause a crash? let newVC: UIViewController? = nil navigationController?.pushViewController(newVC!, animated: true)
Aanimated parameter cannot be true
BYou cannot push a nil view controller onto the navigation stack
CnavigationController must be force unwrapped
DpushViewController requires a completion handler
Step-by-Step Solution
Solution:
  1. Step 1: Understand pushViewController parameter

    pushViewController requires a non-nil UIViewController instance.
  2. Step 2: Check consequences of nil argument

    Passing nil (via force-unwrap newVC!) causes runtime crash because method expects a valid controller.
  3. Final Answer:

    You cannot push a nil view controller onto the navigation stack -> Option B
  4. Quick Check:

    pushViewController(nil) causes crash [OK]
Quick Trick: Never push nil view controller; always instantiate first [OK]
Common Mistakes:
  • Passing nil instead of a valid view controller
  • Thinking animated parameter causes crash
  • Believing force unwrap is required

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes