[英]Assign Value from Closure to Variable Swift
I'm trying to assign the value I get back from a closure to a variable I have assigned outside the scope of the closure. 我试图将我从闭包中获得的值分配给在闭包范围之外分配的变量。
I want to do this so i'm able to use this var outside my closure in order to be neat and not have all this nested code inside this closure. 我想这样做,因此我可以在我的闭包之外使用此var,以使其整洁,而不必在此闭包内使用所有这些嵌套的代码。
I am using Alamofire for the requests and swify-json to help parse the json. 我正在使用Alamofire来处理请求,并使用swify-json帮助解析json。
I'm getting the following: 我得到以下内容:
Error: variable 'userId' captured by a closure before being initialized
Here is my code calling my closure function: 这是我的代码调用我的闭包函数:
var userId: Int
get()
{
data in
userId = data["used_id"].intValue
}
Here is my implementation of my get() function: 这是我对get()函数的实现:
func get(param: [String: AnyObject] = [String: AnyObject](), completion: (JSON) -> ())
{
Alamofire.request(.GET, "apiendpoint.com", parameters: param)
.responseJSON
{
response in
switch response.result
{
case .Success:
let jsonData = JSON(data: response.data!)
completion(jsonData)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}
Thank you for any and all help! 感谢您提供的所有帮助!
change var userId: Int
to var userId: Int!
将var userId: Int
更改为var userId: Int!
The reason is that the closure is expecting a value to be in the variable when you "capture it". 原因是当您“捕获”闭包时,它期望值包含在变量中。 By using a forcefully unwrapped variable, the closure will be able to capture it as it holds a value of nil, which you can then assign a value to when the closure is called. 通过使用强制展开的变量,闭包将可以捕获它,因为它拥有一个nil值,然后您可以在调用闭包时为其分配一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.