如何在Swift 3中从字典中获取数组 [英] how to get array from dictionary in swift 3

查看:576
本文介绍了如何在Swift 3中从字典中获取数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白如何从字典中获取数组,我已经在这段代码中尝试过,但是我只想获取数组的内容和类型

I don't understand how to get array from dictionary, i have tried in this code but i want get array only content and type

这是我的阵列

{
    wsResponse =     {

  aarti =(
  {
        content = "";
        identifier = "slok_one";
        title = 1;
        type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
    },
            {
        content = "";
        identifier = "slok_two";
        title = 2;
        type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
    },
            {
        content = "";
        identifier = "slok_three";
        title = 3;
        type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
    }

 }
 );
 };

这是我的代码

Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default)
        .responseJSON { response in

            if let status = response.response?.statusCode {
                switch(status){
                case 201:
                    print("example success")
                default:
                    print("error with response status: \(status)")
                }
            }

            //to get JSON return value
            if let array = response.result.value
            {
                let JSON = array as! NSDictionary
                print("\(JSON)")


                let response = JSON["wsResponse"] as! NSDictionary
                let data  = response["aarti"]
            }
 }

我想要这个数组,例如内容,标题,类型

i want array from this ,like content,title,type

提前谢谢

推荐答案

根据JSON,将打印aarti数组中的所有值:

According to the JSON this prints all values in the aarti array:

if let JSON = response.result.value as? [String:Any] {   
   if let response = JSON["wsResponse"] as? [String:Any],
      let aarti = response["aarti"] as? [[String:Any]] {

         for item in aarti {
            let content = item["content"] as! String
            let identifier = item["identifier"] as! String
            let title = item["title"] as! Int
            let type = item["type"] as! String
            print(content, identifier, title, type)
        }
   }
}

在Swift中基本上不使用NSDictionary / NSArray.

Basically do not use NSDictionary / NSArray in Swift.

如果要将所有content值放入数组中,请使用flatMap.该行可以代替整个重复循环.

If you want to put all content values in an array use flatMap. The line can replace the whole repeat loop.

 let contentArray = aarti.flatMap { $0["content"] as? String }

PS:如果要根据值创建多个数组,请不要这样做:使用自定义结构或类

PS: If you are going to create multiple arrays from the values don't do that: Use a custom struct or class

这篇关于如何在Swift 3中从字典中获取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆