【问题标题】:Why does Unexpected non-void return value in void function happen? [duplicate]为什么 void 函数中会发生意外的非 void 返回值? [复制]
【发布时间】:2017-10-10 21:57:52
【问题描述】:

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

void 函数中出现意外的非 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
            }
        }
}

【问题讨论】:

  • return 语句返回一个值作为该完成处理程序(闭​​包)的结果,而不是 getURL(name:) 函数。完成处理程序不应返回任何内容。
  • 你应该查一下异步函数的概念。他们使用像这样的完成块操作,而不是返回东西。
  • 您需要使用完成处理程序从闭包中返回值。

标签: ios swift alamofire


【解决方案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
}

【讨论】:

  • 谢谢!这对我有用。
【解决方案2】:

你不能从更近的内部返回值,所以你需要为你的函数添加闭包

func getURL(name: String , completion: @escaping (_ youstring : String) -> (Void) ) -> 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((response.result.value) != nil) {
                    let swiftyJsonVar = JSON(response.result.value!)

                    print(swiftyJsonVar)

                    let videoUrl = swiftyJsonVar["videoUrl"].stringValue

                    print("videoUrl is " + videoUrl)
                     completion (youstring :  )
                      // error happens here
                }
            }
    }

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2017-05-15
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多