2017-05-11 20 views
1

APIからURLを取得し、結果としてURL文字列を返す関数を作成しました。これがなぜ起こるか誰もが知っていなぜvoid関数の予期しない非void戻り値が発生するのですか?

予期しない非空の戻り値void型関数で

:しかし、Xcodeは私にこのエラーメッセージが表示されますか?代わりに返す値の

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 
       } 
      } 
    } 
関連する問題