How is it possible to get the handler of a UIAlertAction in Swift. It is set when initializing however I haven't found any property to get hold on the closure of the action. The closure is of type (UIAlertAction) -> Void however I would like to get the content of the closure so that I have some closure like () -> Void. Is this possible? Thanks for your answers
I've created a subclass for this as followed:
/// An UIAlertAction which saves the handler. Can be used for unit testing the action callback.
final class UIExecutableAlertAction: UIAlertAction {
    private var handler: ((UIAlertAction) -> Swift.Void)?
    static func with(title: String?, style: UIAlertActionStyle, handler: ((UIAlertAction) -> Swift.Void)? = nil) -> UIExecutableAlertAction {
        let action = UIExecutableAlertAction(title: title, style: style, handler: handler)
        action.handler = handler
        return action
    }
    func execute() {
        handler?(self)
    }
}
Which can be used like this:
let myAction = UIExecutableAlertAction.with(title: "title", style: .destructive, handler: { [weak self] _ in
    // Do something
})
                        There is NO member/property exposed by the UIAlertAction class. However we can manage this by ourselves by subclassing UIAlertAction and have some member named, say, "actionHandler" to store that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With