gpt4 book ai didi

syntax - Swift 完成处理程序语法

转载 作者:可可西里 更新时间:2023-11-01 01:43:42 25 4
gpt4 key购买 nike

此代码用于回答此处的问题:

How to make an HTTP request in Swift?

let url = NSURL(string: "http://www.stackoverflow.com")

let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

dataTaskWithURL 的文档说明如下:

func dataTaskWithURL(_ url: NSURL,
completionHandler completionHandler: ((NSData!,
NSURLResponse!,
NSError!) -> Void)?) -> NSURLSessionDataTask

所以看起来第一个代码块的 {(data .... 部分是完成处理程序。我来自 Java 背景,可以这样表达:

dataTaskWithUrl(url, function(data, ....) { .... });

有人可以解释为什么完成处理程序不是方法调用中的第二个参数吗?

最佳答案

这是一个Trailing Closure :

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

关于syntax - Swift 完成处理程序语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com