gpt4 book ai didi

swift - urlSession.dataTaskWithRequest(request)的含义

转载 作者:行者123 更新时间:2023-11-28 08:43:52 27 4
gpt4 key购买 nike

当我在网络开发章节中阅读有关swift的书时,我遇到了一些我看不懂的代码。代码如下:

let sessionTask = urlSession.dataTaskWithRequest(request) {
(data, response, error) in

handler(response, data)
}

这个函数在swift中的原型(prototype)是:

public func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask

可以看到,原型(prototype)有2个参数,一个是request,一个是completionHandler。但是在上面的代码中,它还有一个参数。而且我也无法理解花括号中的代码,3 个变量数据、响应、错误从何而来?我找不到这 3 个变量的任何定义。谁能帮助我理解代码,在此先感谢。

最佳答案

它被称为尾随闭包,如果该函数是最后一个参数,它是将一个函数传递给另一个函数的一种更简洁的方法。同样的代码可以写成:

let sessionTask = NSURLSession.sharedSession()
let request = NSURLRequest()
sessionTask.dataTaskWithRequest(request, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

})

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

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID102

func aFunction(callback: (done: Bool) -> Void) {
let finished = true
callback(done: finished)
}

aFunction { (done) -> Void in
print("we are done \(done)")
}

关于swift - urlSession.dataTaskWithRequest(request)的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826217/

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