从swift中的字典中检索字典数组

时间:2014-06-10 08:43:50

标签: arrays dictionary swift ios8

我有一个json响应,其中包含一系列字典。我希望能够将该数组复制到现有数组中。

我在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);
    });

在swift中它必须是这样的:

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);
            });

但是这给了我以下错误:

'AnyObject' is not convertible to 'AnyObject[]&#39;

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

问题在于您声明AnyObject[]: 错误(&#39; AnyObject&#39;无法转换为&#39; AnyObject []&#39; )明确指出,没有数组初始化

如果初始化者应该是数组值然后用于AnyObject[],请先检查响应值。

替换:

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

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