Marat
Marat

Reputation: 6703

Swift 3: index out of range error

I'm new to iOS. Doing project by watching tutorial which is written using Swift 2.
It works when author runs app but not in my case.

ViewController:

var books = [[String: AnyObject]]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    searchBar.delegate = self
}

And the extension

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath)

        // error on this line
        if let volumeInfo = self.books[indexPath.row]["volumeInfo"] as? [String: AnyObject] {
            cell.textLabel?.text = volumeInfo["title"] as? String
            cell.detailTextLabel?.text = volumeInfo["subtitle"] as? String
        }

        return cell
    }
}

The console output:

enter image description here

Please, help me to identify what is the cause.

Upvotes: 0

Views: 5897

Answers (2)

vadian
vadian

Reputation: 285270

You have to return books.count from numberOfRowsInSection, never "hard-code" that value if it's related to the data source array.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}

PS: In Swift 3 you should use [String:Any] rather than [String:AnyObject]

Upvotes: 2

Tyler Rolfe
Tyler Rolfe

Reputation: 194

I'm assuming a lot about your project but if you only have one section in your tableView, which is the default, you shouldn't use indexPath.section for your books dictionary. You should use indexPath.row as seen below

Change -

if let volumeInfo = self.books[indexPath.section]["volumeInfo"] as? [String: AnyObject]

To -

if let volumeInfo = self.books[indexPath.row]["volumeInfo"] as? [String: AnyObject] {

Upvotes: 2

Related Questions