Reputation: 449
There seem to be 3 different ways to write the handler of a UIAlertAction. Each of the below seem to do the same/expected thing i want them to
// 1.
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) -> Void in
print("a")
})
// 2.
let okAction = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) in
print("b")
})
// 3.
let okAction = UIAlertAction(title: "OK", style: .Default) { (action) in
print("c")
}
// OUTPUT:
// a
// b
// c
Are these all making handlers? What are the differences and is one best to use?
Upvotes: 0
Views: 116
Reputation: 891
Its all same. Since swift is a strongly typed language no need to define the action as UIAlertAction
, coz UIAlertAction
's init method defined it as a UIAlertAction
.
Just like when you define an Array with Some custom class when retrieving values from that array you don't need to cast it like in Objective C.
So any of above 3 ways are OK, number 3 seems clear and shot for my taste :)
Also since it doesn't have a return type no need to mention Void(return type) too. If it has a return type you need to mention that like param -> RetType in
method { param -> String in
return "" // should return a String value
}
Upvotes: 0
Reputation: 55815
They are all the same, it's mostly a matter of syntactic style you prefer. Option 3 uses type inference and the trailing closure syntax, which is generally preferred as it's concise and gets rid of the extra set of parentheses as it moves the last argument closure outside of the function call. You could one-up option 3 by removing the parentheses around action
, those aren't needed either.
More on this is explained in the Swift Programming Language book, see the section on Closures.
Upvotes: 3