【问题标题】:Retrieve array of dictionaries, from a dictionary in swift从 swift 中的字典中检索字典数组
【发布时间】:2014-06-10 08:43:49
【问题描述】:

我有一个 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[]'

任何帮助将不胜感激!

【问题讨论】:

    标签: arrays dictionary swift ios8


    【解决方案1】:

    问题在于你声明AnyObject[]: 错误('AnyObject' is not convertible to 'AnyObject[]')明确指出,没有数组初始化。

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

    替换:

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

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

    【讨论】:

    • 我摆脱了第一个错误。现在应用程序运行,但立即崩溃。这是一张图片:imgur.com/3RL60yf。感谢您的帮助
    猜你喜欢
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2014-08-23
    相关资源
    最近更新 更多