2016-11-24 33 views
-1

我想從方法(使用異步調用)返回一個數組(arr)。我在該方法中實現了completionHandler,但我無法使用我的方法獲取我的陣列:Cast from '(@escaping ((Array<Any>) -> Void)) ->()' to unrelated type '[[String : Any]]' always failsCompletionHandler在Swift 3中使用異步調用

我該如何解決這個問題?

這裏是我的代碼:

func dataWithURL(completion: @escaping ((_ result:Array<Any>) -> Void)) { 
    let urlString = "https://api.unsplash.com/photos/?client_id=71ad401443f49f22556bb6a31c09d62429323491356d2e829b23f8958fd108c4" 
    let url = URL(string: urlString)! 
    let urlRequest = URLRequest(url: url) 
    let config = URLSessionConfiguration.default 
    let session = URLSession(configuration: config) 

    var arr = [[String:String]]() 
    let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in 
     // do stuff with response, data & error here 
     if let statusesArray = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String: Any]] { 
      for item in statusesArray! { 
       let photos = item["urls"] as? [String: Any] 
       let photo = photos?["small"] as? String 
       let myDictionary = [ 
        "name": "test", 
        "imageURL": photo] 
       arr.append(myDictionary as! [String : String]) 
      } 
      print(arr) 
      completion(arr) 
     } 
    }) 

    task.resume() 
} 

當我想要得到我的數組:

lazy var photos: [Photo] = { 

    var photos = [Photo]() 

// HERE THE ERROR APPEARS 
guard let data = self.dataWithURL as? [[String: Any]] else { return photos } 
    for info in data { 
     let photo = Photo(info: info) 
     photos.append(photo) 
    } 
    return photos 
}() 
+1

我想你應該搜索如何調用函數,如何使用閉包,以及如何使用閉包作爲完成塊第一。 –

回答

4

dataWithURL發生在回調(完成處理),因此,你只能訪問結果回調。

self.dataWithURL { result in 
//do stuff with the result 
} 

但是,上面的代碼的問題是,你期待dataWithURL返回它沒有的結果。它返回void。

另一個問題是您正在嘗試將dataWithURL的結果用於屬性。訪問惰性變量photos的調用不會產生結果(至少在第一次調用時),因爲調用dataWithURL是異步的(立即返回)。

1

你好像也是xcode_Dev昨天問了this的問題。

我寫了這個問題評論:它包含一個異步任務

這仍然是正確的

不能從函數返回(或計算變量)的東西。

dataWithURL是一個異步函數,它不返回任何東西,但你必須傳遞一個在返回時調用的閉包。

首先,數組顯然是[[String:String]](字典數組具有字符串鍵和字符串值),所以這是非常愚蠢的使用更加不明類型的[Any]

func dataWithURL(completion: @escaping ([[String:String]]) -> Void) { 

在斯威夫特3只指定型在沒有下劃線和參數標籤的聲明中。


你要調用的函數是這樣的:再次

dataWithURL { result in 
    for item in result { // the compiler knows the type 
     print(item["name"], item["imageURL"]) 
    } 
} 

:還有就是dataWithURL沒有返回值。關閉被稍後調用。

相關問題