I\'m creating a UITableViewController with Swift language and in a method
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: N
All you have to do to access NSIndexPath
's row and section are to import the header of the file where these extensions to the base NSIndexPath
class are defined.
If you don't, your class will act like row and section just don't exist on an instance of NSIndexPath
.
The row and section extensions to NSIndexPath
are declared within the UIKit framework inside UITableView.h
.
To fix this problem, all you need to do is import UITableView.h
into your class. That's it.
Here is where the extensions to the class are defined in UITableView.h in Objective-C. I'm sure Swift has a similar section.
// This category provides convenience methods to make it easier to use an NSIndexPath to represent a section and row
@interface NSIndexPath (UITableView)
+ (instancetype)indexPathForRow:(NSInteger)row inSection:(NSInteger)section;
@property (nonatomic, readonly) NSInteger section;
@property (nonatomic, readonly) NSInteger row;
@end
Use .item instead of .row
cell.textLabel.text = self.dataStore[indexPath.item]
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.
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.