Swifter
Swifter

Reputation: 55

Error with tableview

I'm new to Swift and IOS programming but I am trying to get some data to load using a table view but I get an error that I have never seen before. Can someone please help me out. The error is showing up on the line where I am trying to pass the cell text label my array that I created. The error is "Could not find an overload for subscript that accepts the supplied arguments" enter image description here

import UIKit

class ViewController: UIViewController, UITableViewDelegate {


    var cellContent = [1,2,3]


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }




    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return cellContent.count
    }



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

        var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        cell.textLabel?.text  = cellContent[indexPath.row]
        return cell

    }

Upvotes: 0

Views: 119

Answers (3)

user3821934
user3821934

Reputation:

You have to use strings for text labels. This will fix your error:

var cellContent = ["1","2","3"];

Upvotes: 1

Syed Tariq
Syed Tariq

Reputation: 2928

Swift is treating cellContent as an integer array. You need to either (1) use cell.textLabel?.text = cellContent[indexPath.row] as String or change the array to var cellContent = ["1","2","3"]

Upvotes: 2

Dima
Dima

Reputation: 23634

Looks like the error is a little misleading. The actual issue here seems to be that you are trying to set an Int as a String property. You can do that like this:

cell.textLabel?.text  = String(cellContent[indexPath.row])

With this change, your code works fine for me.

Upvotes: 2

Related Questions