I currently have code that will take the json data I give it and parse it however I have everything wrapped in a for loop and I don't know how to take it out.
JSON data:
[
{
"id": 1,
"displayName": "Jacob Blacksten",
"department": "DF",
"mamager": "San",
"office": "NYC",
"util": 2
}
]
Working code:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
guard let array = json as? [Any] else {return}
for user in array {
guard let userDict = user as? [String: Any] else {return}
guard let id = userDict["id"] as? Int else { return }
guard let name = userDict["displayName"] as? String else { return}
guard let department = userDict["department"] as? String else {return}
guard let manager = userDict["mamager"] as? String else {return}
guard let office = userDict["office"] as? String else {return}
guard let util = userDict["util"] as? Int else {return}
print(id)
print(name)
print(department)
print(manager)
print(office)
print(util)
}
} catch{
print(error)
}
You will notice everything is inside a for loop creating an array of all "users". However I only have one user and I want to be able to pull out say "id" and use it as a variable to later print it out in a label in my app. I hope this makes sense. I basically just want to manipulate this JSON data so that way I can use it and print them in labels in my app.
mutableContainersto an immutable constant (let json)?