Writing handler for UIAlertAction Writing handler for UIAlertAction ios ios

Writing handler for UIAlertAction


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


Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handler argument. Observe:

func someHandler(alert: UIAlertAction!) {    // Do something...}alert.addAction(UIAlertAction(title: "Okay",                              style: UIAlertActionStyle.Default,                              handler: someHandler))


You can do it as simple as this using swift 2:

let alertController = UIAlertController(title: "iOScreator", message:        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in        self.pressed()}))func pressed(){    print("you pressed")}    **or**let alertController = UIAlertController(title: "iOScreator", message:        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in      print("pressed") }))

All the answers above are correct i am just showing another way that can be done.