Rorschach Rorschach - 1 year ago 124
Swift Question

How to access JSON in '(String, JSON)'

I am trying to get the value in a '(String, JSON)'

When printed the whole SwiftyJSON object looks like:

("0", {
"created_at" : "2016-05-01T14:39:10.000Z",
"user_id" : 2,
"id" : 75,
"item_id" : 172,
"updated_at" : "2016-05-01T14:39:10.000Z"

Assume the object is called: jstring_info

I would like to do this:

let item_id = jstring_info[1]["item_id"]

so that
would give 172

But this is not the proper syntax, and I cannot find it anywhere online.

The error that the above code gives is
Type 'Element' (aka '(String, JSON)') has no subscript members

Answer Source

It's a Tuple, So that you access it like this.

   let itemId = jstring_info.1["item_id"]

Just start typing the instance in you code, Xcode will autocomplete the objects inside the tuple, after selecting your JSON object you can access the key inside it.

These example will help you a bit.

        let person : (String,Int) = ("alvin", 789)
        person.0 // represents String alvin
        person.1 // represents Integer 789

And this,

        let person : (name : String,age : Int) = ("alvin", 789) // represents name alvin
        person.age // represents age 789
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download