NSIndexPath? 在Swift中没有成员名“行”错误

我正在用Swift语言和方法创build一个UITableViewController

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

我得到这个错误

NSIndexPath? 在Swift中没有成员名“行”错误

我不明白为什么。

这是我的代码

 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 } } 

那么,如何设置cell.text与数组dataStore元素?

你可以打开可选的indexPath参数, if let...

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

或者如果你确定indexPath不是nil ,你可以强制解包!

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

请记住, indexPath! 在一个零值将是一个运行时exception,所以最好的做法是解开它,如第一个例子。

你可以在这个调用中使用可选的链接语法(如果indexPath nil将cell.textLabel.text设置为nil ):

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

或者显式解开它(如果indexPath nil则会导致运行时错误):

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

或者使用@NateCook提供的更为详细的if let语法。

所有你需要做的访问NSIndexPath的行和部分是导入文件的头文件,这些扩展到基本的NSIndexPath类被定义。

如果你不这样做,你的类将像行和部分一样行事,就是不存在于NSIndexPath一个实例上。

NSIndexPath的行和段扩展在UITableView.h的UIKit框架内声明。

要解决这个问题,你需要做的就是将UITableView.h导入到你的类中。 而已。

Objective-C中的UITableView.h中定义了类的扩展。 我相信Swift有一个类似的部分。

 // 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