johnyDiOS
johnyDiOS

Reputation: 21

how to get array from dictionary in 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

This is my array

{
    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";
    }

 }
 );
 };

Here is my code

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

thank you in advance

Upvotes: 0

Views: 14963

Answers (2)

234 Shk
234 Shk

Reputation: 326

if someone want to get dictionary of array and use it in tableview declaration:

var list:[Any] = []

and initialisation :

self.list =  (self.ListDic?["data"] as! NSArray!) as! [Any]

and use:

let dictObj = self.list[indexPath.row] as! NSDictionary
print("object value: ",dictObj["text"] as! String)

Upvotes: 0

vadian
vadian

Reputation: 285039

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

Basically do not use NSDictionary / NSArray in Swift.

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: If you are going to create multiple arrays from the values don't do that: Use a custom struct or class

Upvotes: 3

Related Questions