一尘不染

为什么在void函数中会发生意外的非void返回值?

swift

我创建了一个从API获取URL并返回URL字符串作为结果的函数。但是,Xcode给我此错误消息:

void函数中非预期的非无效返回值

有谁知道为什么会这样吗?

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
            }
        }
}

阅读 198

收藏
2020-07-07

共1个答案

一尘不染

使用闭包而不是返回值:

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
}
2020-07-07