Writing handler for UIAlertAction

Steve Marshall picture Steve Marshall · Jun 12, 2014 · Viewed 114.6k times · Source

I'm presenting a UIAlertView to the user and I can't figure out how to write the handler. This is my attempt:

let alert = UIAlertController(title: "Title",
                            message: "Message",
                     preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                            handler: {self in println("Foo")})

I get a bunch of issues in Xcode.

The documentation says convenience init(title title: String!, style style: UIAlertActionStyle, handler handler: ((UIAlertAction!) -> Void)!)

The whole blocks/closures is a little over my head at the moment. Any suggestion are much appreciated.

Answer

jbman223 picture jbman223 · Jun 12, 2014

Instead of self in your handler, put (alert: UIAlertAction!). This should make your code look like this

    alert.addAction(UIAlertAction(title: "Okay",
                          style: UIAlertActionStyle.Default,
                        handler: {(alert: UIAlertAction!) in println("Foo")}))

this is the proper way to define handlers in Swift.

As Brian pointed out below, there are also easier ways to define these handlers. Using his methods is discussed in the book, look at the section titled Closures