-5

Well, I have a server response with this:

{
 cars =     (
 {
 "color" = red;
 "model" = ferrari;
 "othersAtributes" = others atributes;
 },{
 "color" = blue;
 "model" = honda;
 "othersAtributes" = others atributes;
 },{
 "color" = green;
 "model" = ford;
 "othersAtributes" = others atributes;
 },{
 "color" = yellow;
 "model" = porshe;
 "othersAtributes" = others atributes;
 }
 )
 }

I need a list of model cars. an array of models cars, to set to a list.

2 Answers 2

0

First of all you need to convert the raw response from the server to a Swift Dictionary.

let payload = [
  "cars": [
    [
      "color": "red",
      "model": "ferrari",
      "othersAtributes": "others atributes"
    ],
    [
      "color": "blue",
      "model": "honda",
      "othersAtributes": "others atributes"
    ],
    [
      "color": "green",
      "model": "ford",
      "othersAtributes": "others atributes"
    ],
    [
      "color": "yellow",
      "model": "porshe",
      "othersAtributes": "others atributes"
    ]
  ]
]

Then

let models: [String] = payload["cars"]!.map({ $0["model"] as! String })
print(models)

will give you ["ferrari", "honda", "ford", "porshe"].

(You might want to get replace the force unwraps ! with safer error handling mechanisms.)

Sign up to request clarification or add additional context in comments.

5 Comments

how I can convert? like this? let payload = response as? [String: Any] ?
I assume the server payload is in standard JSON form and you are requesting it using NSURLSessionDataTask so that you get a Data object. Then the answer will be what @Vignesh J posted. Although I'd recommend using [String: Any] to be more Swift-y. let payload: [String: Any]= NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String: Any]
I do it with alamofire
and response is a any object
You should be able to cast an AnyObject to a Dictionary. I think here is a perfect example github.com/Alamofire/Alamofire/blob/…
0

Try this snippet. Not tested perfectly. I am guessing cars is an Array:

 var modelsArray = [String]()
        for index in cars.enumerated(){
            let model = cars[index].value(forKey: "model")
            modelsArray.append(model)
        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.