1

I am using this library to parse an API endpoint that returns an array: https://github.com/SwiftyJSON/SwiftyJSON

I am grabbing an array fetched from a JSON response and I am trying to feed it into a table.

Right after my class in my view controller is declared, I have

var fetched_data:JSON = []

Inside of my viewDidLoad method:

let endpoint = NSURL(string: "http://example.com/api")
        let data = NSData(contentsOfURL: endpoint!)
        let json = JSON(data: data!)
        fetched_data = json["posts"].arrayValue

To feed the table, I have:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell1")! as UITableViewCell
        cell.textLabel?.text = self.fetched_data[indexPath.row]
        return cell      
    }

I am getting this error, when trying to set the cell textLabel:

Cannot subscript a value of a type ‘JSON’ with an index type of ‘Int’

How do I do this properly and get this to work?

1 Answer 1

2

You are declaring fetched_data as JSON

var fetched_data:JSON = []

but you are assigning Array to it:

fetched_data = json["posts"].arrayValue

Lets change the type to array of AnyObject:

var fetched_data: Array<AnyObject> = []

and then assigning should be like this (we have [AnyObject] so we need to cast):

if let text = self.fetched_data[indexPath.row] as? String {
    cell.textLabel?.text = text
}

Edit: You also need to remember to assign correct Array, by doing arrayObject instead of arrayValue:

fetched_data = json["posts"].arrayObject
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Now, in my vieDidLoad method, I am getting: Cannot assign value of type ‘[JSON]’ to type ‘Array<String>’
Thank you sooooo much, I really appreciate it!

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.