为什么void函数中出现意外的非void返回值? [英] Why does Unexpected non-void return value in void function happen?
本文介绍了为什么void函数中出现意外的非void返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个从API获取URL的函数,并返回URL字符串作为结果。但是,Xcode给出了以下错误消息:
I created a function to get URL from API, and return URL string as the result. However, Xcode gives me this error message:
void函数中出现意外的非void返回值
Unexpected non-void return value in void function
有谁知道为什么会这样?
Does anyone know why this happens?
func getURL(name: String) -> String {
let headers: HTTPHeaders = [
"Cookie": cookie
"Accept": "application/json"
]
let url = "https://api.google.com/" + name
Alamofire.request(url, headers: headers).responseJSON {response in
if((response.result.value) != nil) {
let swiftyJsonVar = JSON(response.result.value!)
print(swiftyJsonVar)
let videoUrl = swiftyJsonVar["videoUrl"].stringValue
print("videoUrl is " + videoUrl)
return (videoUrl) // error happens here
}
}
}
推荐答案
使用闭包而不是返回值:
Use closure instead of returning value:
func getURL(name: String, completion: @escaping (String) -> Void) {
let headers: HTTPHeaders = [
"Cookie": cookie
"Accept": "application/json"
]
let url = "https://api.google.com/" + name
Alamofire.request(url, headers: headers).responseJSON {response in
if let value = response.result.value {
let swiftyJsonVar = JSON(value)
print(swiftyJsonVar)
let videoUrl = swiftyJsonVar["videoUrl"].stringValue
print("videoUrl is " + videoUrl)
completion(videoUrl)
}
}
}
getURL(name: ".....") { (videoUrl) in
// continue your logic
}
这篇关于为什么void函数中出现意外的非void返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文