Bird
0
0

You want to create a toggle switch that updates a label text to "ON" or "OFF" when toggled. Which code snippet correctly implements this behavior?

hard📝 Application Q15 of 15
iOS Swift - User Input and Forms
You want to create a toggle switch that updates a label text to "ON" or "OFF" when toggled. Which code snippet correctly implements this behavior?
let toggle = UISwitch()
let label = UILabel()

// Which switchChanged method is correct?
A@objc func switchChanged(_ sender: UISwitch) { label.text = sender.isOn ? "ON" : "OFF" }
B@objc func switchChanged() { label.text = toggle.isOn ? "ON" : "OFF" }
C@objc func switchChanged(_ sender: UISwitch) { if sender.isOn == false { label.text = "ON" } else { label.text = "OFF" } }
D@objc func switchChanged(_ sender: UISwitch) { label.text = "ON" }
Step-by-Step Solution
Solution:
  1. Step 1: Check method signature and parameter

    The action method must accept the sender UISwitch to get its current state.
  2. Step 2: Verify label text update logic

    @objc func switchChanged(_ sender: UISwitch) { label.text = sender.isOn ? "ON" : "OFF" } uses a ternary operator to set label text to "ON" if switch is on, else "OFF", which is correct.
  3. Step 3: Review other options

    @objc func switchChanged() { label.text = toggle.isOn ? "ON" : "OFF" } lacks sender parameter; @objc func switchChanged(_ sender: UISwitch) { if sender.isOn == false { label.text = "ON" } else { label.text = "OFF" } } reverses ON/OFF logic; @objc func switchChanged(_ sender: UISwitch) { label.text = "ON" } always sets "ON" ignoring switch state.
  4. Final Answer:

    @objc func switchChanged(_ sender: UISwitch) { label.text = sender.isOn ? "ON" : "OFF" } -> Option A
  5. Quick Check:

    Use sender.isOn with ternary to update label [OK]
Quick Trick: Use sender.isOn ? "ON" : "OFF" to update label [OK]
Common Mistakes:
  • Forgetting sender parameter in action method
  • Reversing ON and OFF text logic
  • Ignoring switch state and setting fixed text

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes