gpt4 book ai didi

swift - 需要关于关闭/完成处理程序的说明

转载 作者:可可西里 更新时间:2023-11-01 02:01:44 26 4
gpt4 key购买 nike

我一直在关注视频教程,并编写了以下代码:

func downloadWeatherDetails(completed: ()->() ) {

let currentWeatherURL = URL(string: CURRENT_WEATHER_URL)!

Alamofire
.request(currentWeatherURL)
.responseJSON(completionHandler: { response in
let result = response.result
print(result)
})
completed()
}

所以基本上,我的理解如下。 .responseJSON 处理程序允许您在请求被触发后调用代码。它允许您指定一个 completionHandler,在我的例子中,它是闭包:

{ response in
let result = response.result
print(result)
}

但是,我不明白“response”关键字的实际含义。我研究了闭包的用法,发现语法是:

{(param) -> returnType in { code here }

因此,“response”关键字是参数吗?如果是这样,它是如何声明的,数据来自哪里?数据是如何传递到“响应”对象中的?另外,为什么只允许一个参数?如果我按如下方式编写,代码将无法运行,例如:

{ (response, test) in
let result = response.result
print(result)
}

我真的很感激对此进行详尽的解释,因为我在网上其他地方找不到任何帮助。看了苹果的《The Swift Programming Language》,看了一大堆不同的解释,还有类似的问题,还是没有完全理解。

Just to clarify, I do not believe my question is a duplicate since my question revolves primarily on the captured value stored in response rather than the syntax of closures as a whole. I went through the linked question while trying to figure out my own problem, but it did not help me sufficiently.

需要稍微说明一下:

Is it always the case that when a method takes a closure as one of its parameters, for example, .testMethod(testParam: (String) -> ()) and would thus in practice be used: .testMethod(testParam: { (capturedVar) in statements} (correct me if im wrong), is it always the case that the parameter of the closure ((String) in this case) will be captured and stored in capturedVar? Will there always be data passed into the variable you define? Or is this cycle specific to alamofire?

最佳答案

Swift 闭包定义为:

{ (parameters) -> return_type in
statements
}

也就是说,括号中的名称是闭包捕获的变量,-> type是可选的返回类型(可选,因为编译器通常可以推断它)。 Alamofire 的 responseJSON方法捕获 DataResponse<Any>参数,您可以随意命名,但通常只命名为 response .然后您可以在该闭包内访问它。

此外,您的 completed() call 应该在responseJSON里面调用,而不是在外面,否则它会立即被调用。

关于swift - 需要关于关闭/完成处理程序的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767394/

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