Bird
0
0

What will be the output when the following Swift code executes and the button is tapped?

medium📝 Predict Output Q4 of 15
iOS Swift - SwiftUI Basics
What will be the output when the following Swift code executes and the button is tapped?
let button = UIButton()
button.addTarget(self, action: #selector(showAlert), for: .touchUpInside)

@objc func showAlert() {
  print("Alert shown")
}
ANothing happens
BApp crashes due to missing selector
CPrints "Alert shown" to the console
DButton title changes to "Alert shown"
Step-by-Step Solution
Solution:
  1. Step 1: Understand addTarget behavior

    The button triggers the showAlert method when tapped.
  2. Step 2: Analyze showAlert method

    The method prints "Alert shown" to the console.
  3. Final Answer:

    Prints "Alert shown" to the console -> Option C
  4. Quick Check:

    Method is correctly linked and prints output [OK]
Quick Trick: Selector calls method printing output on tap [OK]
Common Mistakes:
  • Assuming UI changes without code
  • Expecting crash without selector error
  • Thinking nothing happens without UI feedback

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes