为什么会在 void 函数中出现 Unexpected non-void 返回值? [英] Why does Unexpected non-void return value in void function happen?

查看:39
本文介绍了为什么会在 void 函数中出现 Unexpected non-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
            }
        }
}

推荐答案

使用闭包代替返回值:

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 函数中出现 Unexpected non-void 返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆