2017-05-11 63 views
1

我创建了一个函数来从API获取URL,并返回URL字符串作为结果。然而,Xcode中给了我这个错误消息:void函数为什么在void函数中出现意外的非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 
      } 
     } 
} 
+1

return语句返回值作为完成处理程序(闭​​包)的结果,而不是'getURL(name:)'函数。完成处理程序不会返回任何内容。 – Alexander

+0

您应该查看异步函数的概念。它们像这样完成块操作,而不是返回事物。 – Connor

+0

您需要使用完成处理程序才能从闭包中返回值。 –

回答

5

使用封闭的,而不是返回值:

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

谢谢!这对我有用。 – Wei

0

你不能从内部接近这样的返回值,你需要关闭添加到您的功能

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 
       } 
      } 
    } 
相关问题