Anuj
Anuj

Reputation: 7067

iOS8 Trailing Closures in Swift

let callActionHandler = { (action:UIAlertAction!) -> Void) in
        let alertMessage = UIAlertController(title: "Service Unavailable", message: "Sorry, the call feature is not available yet. Please retry later", preferredStyle: UIAlertControllerStyle.Alert)
        alertMessage.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alertMessage, animated: true, completion: nil)
    };    

// Code Snippet 1
let callAction = UIAlertAction(title: "Call" + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default ) { (action:UIAlertAction!) -> Void in
        println("check this out")
}

// Code Snippet 2
let callAction = UIAlertAction(title: "Call" + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) -> Void in  
        println("Lets check this out")
})

// Code Snippet 3
let callAction = UIAlertAction(title: "Call" + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default , handler: callActionHandler)

Thanks

Upvotes: 4

Views: 601

Answers (1)

Rob
Rob

Reputation: 437552

You asked:

  1. What is the difference between Code Snippet 1 and Code Snippet 2 ?

Code snippet 1 is is employing the "trailing closure" rendition of snippet 2. See Trailing Closure discussion in The Swift Programming Language: Closures, which says:

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is a closure expression that is written outside of (and after) the parentheses of the function call it supports

So snippet 1 and snippet 2 are doing precisely the same thing.

  1. Which out of Snippet 1 or Snippet 2 is a better representation and should be used ?

Generally one would prefer the trailing closure syntax of snippet 1 because it's more concise. But use whatever makes your code's intent both clear and concise.

  1. What does Code Snippet 1 exactly mean? Is it some sort of property (completion) observing in swift?

No, it is exactly the same thing as snippet 2.

  1. The way iOS8 wants us to write is shown in Snippet 1, i.e., when I press enter while Xcode autocompletes, it gets converted to Snippet 1. Should we use Code Snippet 1 or still prefer using Snippet 2/3 as they are easily understood?

Again, use whatever you prefer and is most clear and concise. Generally people avail themselves of the trailing closure syntax when possible.


Personally, in addition to trailing closure syntax, I might avail myself of inferred types of the parameter and dot syntax of the enum to simplify this further:

let callAction = UIAlertAction(title: "Call 123-000-\(indexPath.row)", style: .default) { action in
    print("check this out")
}

Upvotes: 4

Related Questions