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

后端 未结 4 1141
迷失自我
迷失自我 2020-12-10 11:12

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

override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: N         


        
相关标签:
4条回答
  • 2020-12-10 11:41

    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
    
    0 讨论(0)
  • 2020-12-10 11:42

    Use .item instead of .row

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

    0 讨论(0)
  • 2020-12-10 11:46

    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.

    0 讨论(0)
  • 2020-12-10 11:52

    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.

    0 讨论(0)
提交回复
热议问题