Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...