Dimitri T Dimitri T - 1 year ago 133
Swift Question

how to return value from nested array - swift 3

My api query is returning several values in an array (as below), which I need to use for further functions. How do I retrieve the value 60, which is nested?

My code eg

let uid = value["uid"] as? String
works well to return uid and name.
But for
let rest = value["field_resting_bpm"] as? String
it returns nil.

How do I correct this line to return the nested value '60'?:

let rest = value["field_resting_bpm"] as? String'

the api query is:

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]

var checkUserEndpoint: String = "https://example.site/ios1/user/1.json"

Alamofire.request(.GET, checkUserEndpoint, parameters: nil, headers: headers, encoding: .JSON)
.responseJSON { response in
guard response.result.error == nil else {
print("ran alamofire")
//got an error in getting the data, need to handle it
print("error calling GET")

guard let value = response.result.value else {
print("no result data received when calling GET")
// return UID
print("ran alamofire")
var datareturned = JSON(value)
print("VALUE: \(value)")

it returns this in my console:

uid = 1;
name = "Guest User";
"field_resting_bpm" = {
und = (
value = 60;

UPDATE: this field is an Integer in Drupal user account settings. I have added a text field (so it should return a string), named field_rest_bpm_string, also for testing

the json on the site returns:


Answer Source

NOTE: Code is in Swift 3 but you can easily convert that in swift 2. SwiftyJSON version code is same in 2 and 3.

If you are using SwiftyJSON then things are pretty much simpler

let value = datareturned["field_resting_bpm"]["und"][0]["value"].stringValue

If you are not using SwiftyJSON

let rest = value["field_resting_bpm"] as? NSDictionary
let und = (rest?.value(forKey: "und") as! NSArray).object(at: 0) as! NSDictionary
let yourValue = und.value(forKey: "value") as! String

Something like this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download