Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSIndexPath? does not have a member name 'row' error in Swift

Tags:

I'm creating a UITableViewController with Swift language and in a method

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

I'm getting this error

NSIndexPath? does not have a member name 'row' error in Swift

and I don't understand why.

This is my code

import UIKit

class DPBPlainTableViewController: UITableViewController {

    var dataStore: NSArray = NSArray()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.dataStore = ["one","two","three"]

        println(self.dataStore)
    }


    // #pragma mark - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {

        // Return the number of sections.
        return 1
    }

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

        // Return the number of rows in the section.
        return self.dataStore.count
    }


    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        cell.textLabel.text = self.dataStore[indexPath.row]

        return cell
    }

}

Then, how can set the cell.text with the array dataStore element?

like image 753
dpbataller Avatar asked Jun 04 '14 14:06

dpbataller


2 Answers

You can either unwrap the optional indexPath parameter with if let...:

if let row = indexPath?.row {
    cell.textLabel.text = self.dataStore[row]
}

or if you're sure indexPath isn't nil, you can force the unwrapping with !:

cell.textLabel.text = self.dataStore[indexPath!.row]

Just keep in mind that indexPath! on a nil value will be a runtime exception, so it's better practice to unwrap it as in the first example.

like image 60
Nate Cook Avatar answered Sep 19 '22 21:09

Nate Cook


You can use the optional chaining syntax for this call (setting cell.textLabel.text to nil if indexPath is nil):

cell.textLabel.text = indexPath? ? self.dataStore[indexPath!.row] : nil

or explicitly unwrap it (causing a runtime error if indexPath is nil):

cell.textLabel.text = self.dataStore[indexPath!.row]

or use the more verbose if let syntax suggested by @NateCook.

like image 40
ipmcc Avatar answered Sep 18 '22 21:09

ipmcc