Marat Marat - 1 month ago 11
iOS Question

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.

Answer

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]