Reputation: 2575
I am attempting to use SwiftyJSON to parse some data from a server.
For example, say the JSON returned from the server is:
{
"data":{
"id":"92",
"name":"harry",
"username":"Hazza"
},
"error":false
}
I would like to get the username string and so to do this I obtain the data object using:
let data = json["data"].dictionaryValue
Then in order to grab the username string I would expect to be able to do
let username = data["username"].stringValue
However this returns an error saying '(String, JSON) does not have a member named '.stringValue'.
Where am I going wrong with this seemingly simple problem?
Thank you.
Upvotes: 4
Views: 9215
Reputation: 1865
For Swift 3/4
guard let username = json["data"]["username"].string else { return nil }
Upvotes: 1
Reputation: 2480
While the above will work, The real issue was you needed to unpack the dict value:
let username = data["username"]!.stringValue
Upvotes: 3
Reputation: 3233
What you should do is:
if let username = json["data"]["username"].string {
println(username)
}
Upvotes: 9