0

There are already posts talking about this, but I am still not able to figure out my problem.

I am accessing my database and am converting the response into a JSON object - that part is working fine. Here is the code for that. joArray now has the data I need.

//Convert data to json object
let joArray : NSArray
do {
    joArray = try JSONSerialization.jsonObject(with: data, options: []) as! NSArray
}
catch  {
    print(responseString)
    print("error trying to convert data to JSON")
    return
 }

If I print out joArray . . .

print(joArray)

. . . this is what I get.

(
        {
        FirstName = Bob;
    },
        {
        FirstName = Bill;
    }
)

How can I put this data into a swift array so that it looks like this?

let FirstNameArray = ["Bob", "Bill"]

FirstName will always be in the same position, but there will be varying numbers of users (Bob, Bill, Mary, etc.).

1
  • 1
    Hard to jugde without knowing the exact JSON. Your print-out is most like only a small part of it. You get an array of dictionaries. You have to (flat)map the array to your desired format. Side-note: Do not use NSArray in Swift. You defeat the strong type system by throwing away the crucial type information. Use native Array Commented Dec 5, 2016 at 18:12

1 Answer 1

2

You will make life easier for yourself if you use a native Swift array instead. So, start by changing your array definition:

let joArray: [[String: Any]]
do {
  joArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
} catch {
  // etc...
}

Now, it's straightforward to construct the required array:

let FirstNameArray = swiftArray.flatMap { $0["FirstName"] }

You should use flatMap, rather than map, because the given array item might not have a property called "FirstName".

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

Comments

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.