How do I throttle button taps in UIKit with Swift?

In UIKit with Swift, it's often necessary to throttle button taps to prevent multiple rapid executions of a task. Throttling allows you to limit the number of times a function can be invoked over a specific period. Here’s how you can implement throttling for button taps in a simple Swift app.

import UIKit class ViewController: UIViewController { var lastTapTime: Date? @IBOutlet weak var myButton: UIButton! override func viewDidLoad() { super.viewDidLoad() myButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) } @objc func buttonTapped() { let currentTime = Date() if lastTapTime == nil || currentTime.timeIntervalSince(lastTapTime!) > 1.0 { lastTapTime = currentTime performAction() } else { print("Button tap ignored") } } func performAction() { print("Button tapped and action performed") } }

button throttle UIKit Swift iOS development