UIAlertAction
iOS Development
Swift Programming
Mobile App Development
UIKit

Writing handler for UIAlertAction

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

A UIAlertAction handler is the closure that runs when the user taps one of the actions in a UIAlertController. In simple cases, the handler is just a short block of code. In real apps, it often triggers navigation, validation, deletion, or form submission.

The important part is not the syntax of the closure itself. It is writing the handler so that it reads clearly, captures state safely, and performs the right work after the user makes a choice.

Basic Alert Action Handler

A minimal alert with one action looks like this:

swift
1import UIKit
2
3class ViewController: UIViewController {
4    func showAlert() {
5        let alert = UIAlertController(
6            title: "Delete item",
7            message: "This action cannot be undone.",
8            preferredStyle: .alert
9        )
10
11        let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { _ in
12            print("User confirmed delete")
13        }
14
15        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
16
17        alert.addAction(deleteAction)
18        alert.addAction(cancelAction)
19        present(alert, animated: true)
20    }
21}

The closure receives the tapped UIAlertAction, but if you do not need it, _ keeps the code cleaner.

Reading Text Field Values Inside the Handler

A very common pattern is reading user input from an alert text field when the confirm action runs.

swift
1func showRenameAlert() {
2    let alert = UIAlertController(title: "Rename", message: nil, preferredStyle: .alert)
3    alert.addTextField { textField in
4        textField.placeholder = "New name"
5    }
6
7    let saveAction = UIAlertAction(title: "Save", style: .default) { _ in
8        let text = alert.textFields?.first?.text ?? ""
9        print("New name: \(text)")
10    }
11
12    alert.addAction(saveAction)
13    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
14    present(alert, animated: true)
15}

This works well because the handler executes only after the user taps the action.

Capture self Carefully

If the handler refers to instance methods or properties, you are capturing self inside a closure.

That is often fine for short-lived alerts, but in general UIKit closure code should still be written consciously.

swift
let action = UIAlertAction(title: "Retry", style: .default) { [weak self] _ in
    self?.reloadData()
}

Using [weak self] makes the capture explicit and avoids retaining the view controller unexpectedly in more complex situations.

Keep the Handler Small

A handler should usually express intent, not contain the whole business workflow inline.

This is better:

swift
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in
    self?.deleteCurrentItem()
}

Than this:

  • database code
  • networking
  • analytics
  • UI updates
  • validation logic

all packed into one closure body.

Short handlers are easier to read and test because the real work lives in named methods.

Alert Versus Action Sheet

The handler pattern is the same whether the controller style is .alert or .actionSheet. What changes is presentation behavior and the UX meaning of the actions.

So the question “how do I write the handler?” has the same answer in both cases: attach a closure that performs the relevant action when tapped.

Common Pitfalls

A common mistake is putting too much logic directly inside the alert action closure. That makes the alert code harder to follow than it needs to be.

Another mistake is force-unwrapping text field values inside the handler. Alerts are UI input, so defensive reading is safer.

Developers also sometimes capture self strongly without thinking, especially when the closure dispatches additional asynchronous work.

Finally, remember that the handler runs after the user chooses the action, not when the action is added to the alert. If your code appears to run “too early,” the bug is elsewhere.

Summary

  • A UIAlertAction handler is just the closure that runs when the user taps that action.
  • Keep the handler small and move real work into named methods when possible.
  • Read alert text fields inside the handler if the action depends on user input.
  • Use explicit captures such as [weak self] when referencing the view controller.
  • The same closure pattern applies to both alerts and action sheets.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.