2016-11-24 35 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没有返回值。关闭被稍后调用。

相关问题