在快速编码期间,我想从我的函数中获取值,但出现了错误,它显示错误:
错误:使用未解析的标识符'金额
获得"数量"的正确方法是什么?从这个功能?
func UserAmountGET() -> Int{
let url = NSURL(string: myIP + "users/amount")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest){
(data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else{
print("error")
return
}
let json = JSON(data: data!)
let amount = Int(json["data"][0]["username"].stringValue)!
}
task.resume()
return amount // Error: Use of unresolved Identifier 'amount'
}
答案 0 :(得分:-1)
问题是amount
变量在网络请求的闭包范围内,无法从函数主体访问。据推测,您的网络请求可能需要一些时间才能完成,因此您可以使用在网络请求返回时运行的闭包。
func UserAmountGET(completion: @escaping (Int) -> ()) {
let url = NSURL(string: myIP + "users/amount")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest){
(data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else{
print("error")
return
}
let json = JSON(data: data!)
let amount = Int(json["data"][0]["username"].stringValue)!
completion(amount)
}
task.resume()
}
然后你会这样称呼你的方法:
UserAmountGET(completion: { amount in
// use the `amount` value here
})
对于网络请求等异步回调,这种闭包的使用更为自然。