简体   繁体   English

迅速从字典中检索字典数组

[英]Retrieve array of dictionaries, from a dictionary in swift

I have a json response, which among other things contains an array of dictionaries. 我有一个json响应,除其他外,其中包含一个字典数组。 I want to be able to copy that array in to an existing array. 我希望能够将该阵列复制到现有阵列中。

The way I did it in objective-C was like this: 我在Objective-C中做到的方式是这样的:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSError *error = nil;
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        NSArray *venuesArray = responseDictionary[@"response"][@"venues"];

        completion(venuesArray, error);
    });

In swift it has to be something like this: 迅速必须是这样的:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
                var error: NSError?
                let responseDictionary: Dictionary<String, AnyObject> = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as Dictionary
                let venuesArray : AnyObject[] = (responseDictionary as AnyObject).valueForKeyPath("response.venues")
                completionClosure(venues: responseDictionary, error: error);
            });

But this gives me the following error: 但这给了我以下错误:

'AnyObject' is not convertible to 'AnyObject[] ' 'AnyObject' is not convertible to 'AnyObject[]

Any help would be appreciated! 任何帮助,将不胜感激!

The problem is with you declaration of AnyObject[] : The error(' AnyObject' is not convertible to 'AnyObject[]' ) clearly states that, there is no array initialisation. 问题出在您声明AnyObject[] :错误(“ AnyObject”不可转换为“ AnyObject []” )清楚地表明,没有数组初始化。

if The initialiser should be the Array values then use for AnyObject[] , check the responses value first. 如果初始化程序应为Array值,然后用于AnyObject[] ,请首先检查响应值。

Replace: 更换:

let venuesArray : AnyObject[] = (responseDictionary as AnyObject).valueForKeyPath("response.venues")

To

let venuesArray : AnyObject = (responseDictionary as AnyObject).valueForKeyPath("response.venues")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM