您不能
return执行异步任务。您必须改用回调。
添加这样的回调:
completion: (dictionary: NSDictionary) -> Void
解析器方法签名:
func jsonParserForDataUsage(urlFordata: String, completion: (dictionary: NSDictionary) -> Void)
并在您要“返回”的数据可用的地方调用补全:
func jsonParserForDataUsage(urlFordata: String, completion: (dictionary: NSDictionary) -> Void) { print("json parser activated") let urlPath = urlForData guard let endpoint = NSURL(string: urlPath) else { return } let request = NSMutableURLRequest(URL:endpoint) NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in do { guard let dat = data else { throw JSONError.NoData } guard let dictionary = try NSJSONSerialization.JSonObjectWithData(dat, options:.AllowFragments) as? NSDictionary else { throw JSONError.ConversionFailed } completion(dictionary: dictionary) } catch let error as JSonError { print(error.rawValue) } catch let error as NSError { print(error.debugDescription) } }.resume()}现在,您可以将此方法与结尾的闭包一起使用,以获取“返回的”值:
jsonParserForDataUsage("http...") { (dictionary) in print(dictionary)}


