- 第二次编辑 - 我现在正在使用Arpit Jain的建议,但我该如何调用该函数?我希望将函数的结果解析为变量。
getToken(completionHandler: { // here I should do something with in
// what should I do here to pass the result of getToken to variable?
})
- 原始问题 -
我是Swift的完全新手,并试图实现一个API(作为一个学习项目)。但由于我不熟悉语法,因此我在这个PoC中不断出错。
我通过alamofire有一个http请求,我希望testResult包含“succes”或erro。但该函数不断返回“空”
我不知道为什么?
func getToken() -> String{
var testResult: String! = "empty"
let url: String! = "https://the.base.url/token"
let parameters: Parameters = [
"grant_type":"password",
"username":"the_username",
"password":"the_password",
"client_id":"the_clientID",
"client_secret":"the_secret",
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .methodDependent)).validate().responseJSON { response in
switch response.result {
case .success:
testResult = "succes"
case .failure(let error):
testResult = error as! String
}
}
return testResult // this line gives the error
}
答案 0 :(得分:2)
在Swift中,Optional
是一个泛型类型,可以包含一个值(任何类型),或者根本没有值。
在许多其他编程语言中,特定的“哨兵”值通常用于表示缺少值。例如,在Objective-C中,nil(空指针)表示缺少对象。
在Swift中,任何类型都可以选择。可选值可以采用原始类型中的任何值,也可以采用特殊值nil。
可选项定义为?类型后缀:
func getToken(tokenReturned:@escaping (_ stringResponse: String?) -> Void) {
var testResult: String? = "empty"
let url: String! = "https://the.base.url/token"
let parameters: Parameters = [
"grant_type":"password",
"username":"the_username",
"password":"the_password",
"client_id":"the_clientID",
"client_secret":"the_secret",
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .methodDependent)).validate().responseJSON { response in
switch response.result {
case .success:
testResult = "succes"
case .failure(let error):
testResult = error as! String // Crash occurred because you were getting nil here and have not unwrapped testResult
}
tokenReturned(testResult)
}
}
用于调用函数:
self.getToken { (strResponse) in
// Now in strResponse you will get result of testResult
}
在您的情况下,未打开完成处理程序块。试着这样打电话。
答案 1 :(得分:0)
异步调用时可以返回nil。使用闭包作为返回值。
示例
请注意,例如,您可以根据自己的要求进行操作
func getResponseString(url: String, method : HTTPMethod, parameter : [String : AnyObject], callback: @escaping (_ string : String) -> ()) -> Void{
Alamofire.request(API_PREFIX + url, method: method, parameters: parameter).validate().responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! [String : AnyObject]
callback("succes")
}
case .failure(let error):
print(error)
callback("" as! String)
UtilityClass .removeActivityIndicator()
}
}
}
<强>调用强>
self .getResponseString(url: "url", method: .post, parameter: ["email":"" as AnyObject]) { (responseString) in
// responseString your string
}