以下是使用XCode 6.4
针对ios 8.4构建的工作代码NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { response, data, error in
if error != nil {
println("there be an error")
} else {
let image = UIImage(data:data)
self.webimage.image = image
}
})
如果我在XCode auto完成它时双击方法签名的closure部分,我最终会处于这种状态:
Xcode没有将})
放在关闭的末尾,还添加了-> Void in
。这是Xcode 6.4中的错误还是闭包有两种替代语法?
我何时需要completionHandler : { arg, arg arg in
与completionHandler : {(arg,arg,arg) -> Void in //code })
答案 0 :(得分:4)
XCode自动完成指令的方式是“尾随闭包式”。
来自Apple文档:
如果需要将闭包表达式传递给函数作为 函数的最终参数和闭包表达式很长,它可以 相反,将它写为尾随闭包很有用。落后 closure是一个封闭表达式,写在(和之后)之外 它支持的函数调用的括号
如果您想了解有关结尾关闭的更多信息,请在此处向文档报告:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html(参见尾随关闭部分)