简体   繁体   中英

code involving indexPath & NSIndexPath works - but why is it redundant?

I'm getting back to using CloudKit and in the project I'm revisiting, I have a query fetch performed and I am left with an array of CKRecords. I'm setting this array to be displayed via TableController. Anyways, I have this one line of code (which works)... but I am just unsure why I am setting the indexPath as NSIndexPath.

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "dining") as! table1cell
    let restaurant: CKRecord = categories[(indexPath as NSIndexPath).row]
    cell.Name.text = restaurant.value(forKey: "Name") as? String

    return cell

With my other non-CKRecord TableController projects, I know I don't have to set the indexPath to itself, in essence. What am I missing here?

The use of the cast to NSIndexPath is pointless. Simply change the line to:

let restaurant: CKRecord = categories[indexPath.row]

If indexPath is not stored in an explicitly typed var, you probably casted it to avoid a compiler message. If the compiler does not know indexPath is of type NSIndexPath, accessing the .row property would likely cause an error.

Where are you declaring/storing indexPath? What happens when you remove the as NSIndexPath cast?

Edit: re-reading your question, I believe the answer is:

"You are not storing indexPath as itself, you are casting whatever is stored in indexPath to be of type NSIndexPath"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM