1

I have the following problem.

I use Alamofire request. The response is a JSON.

        Alamofire.request(url, method: .get).responseJSON {
        response in
        if response.result.isSuccess {

            print("Success! Got the korosztaly data")
            let koJSON : JSON = JSON(response.result.value!)


           print(koJSON)

        }
        else {
            print("Error \(String(describing: response.result.error))")
        }
    }

The result of the koJSON is the following:

{ "members": [ {"name": "Sarah"}, {"name": "David"}, {"name": "Michael"} ] }

I want to create an Members array and put all of the data into it. The result should be the following

Members = ["Sarah", "David", "Michael"]

1 Answer 1

3

I prefer to use the map function. It will iterate over each item in the array and allow you to pull out the selected information, or do a transformation on it.

if let resp = response.result.value as? [String: AnyObject], 
      let membersArr = resp["members"] as? [[String: String]] {
   let members = membersArr.map { $0["name"] }
}

Output should be as expected.

You can read more about map and other high order functions here

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

7 Comments

"Cast from 'JSON' to unrelated type '[[String : String]]' always fails" - is the message..
"Type 'Any' has no subscript members" is the error message
I have updated the answer, try that. I think Alamofire automatically casts as String: Any
Cannot subscript a value of type '[[String : AnyObject]]' with an index of type 'String' error at your second line.
sorry my mistake, i updated again. first cast should be [String: AnyObject] not [[String: AnyObject]]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.