首页 > 解决方案 > 出现此错误的原因是什么:“NSIndexPath' 不能隐式转换为 'IndexPath';您的意思是使用 'as' 显式转换吗?”

问题描述

在学习 swift 编程的过程中遇到了障碍。这是一个待办事项列表应用程序。我试图了解为什么我会收到此错误:

NSIndexPath' is not implicitly convertible to 'IndexPath'; did you mean to use 'as' to explicitly convert?

对于以下代码块:

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    var toDoItems = [ToDoItem]()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if toDoItems.count > 0 {
            return
        }
        toDoItems.append(ToDoItem(text: "feed the cat"))
        toDoItems.append(ToDoItem(text: "buy eggs"))
        toDoItems.append(ToDoItem(text: "watch WWDC videos"))
        toDoItems.append(ToDoItem(text: "rule the Web"))
        toDoItems.append(ToDoItem(text: "buy a new iPhone"))
        toDoItems.append(ToDoItem(text: "darn holes in socks"))
        toDoItems.append(ToDoItem(text: "write this tutorial"))
        toDoItems.append(ToDoItem(text: "master Swift"))
        toDoItems.append(ToDoItem(text: "learn to draw"))
        toDoItems.append(ToDoItem(text: "get more exercise"))
        toDoItems.append(ToDoItem(text: "catch up with Mom"))
        toDoItems.append(ToDoItem(text: "get a hair cut"))
    }
    
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return toDoItems.count
    }

    func tableView(tableView: UITableView,
        cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("cell",
                forIndexPath: indexPath) as! UITableViewCell
            let item = toDoItems[indexPath.row]
            cell.textLabel?.text = item.text
            return cell
    }
    
}

当我在谷歌上搜索时,无法在任何地方找到此错误消息。为可能导致此类错误的原因而挠头。

代码来自此页面的教程: https ://www.raywenderlich.com/2153-how-to-make-a-gesture-driven-to-do-list-app-like-clear-in-swift-第 1-2 部分

会不会是有些东西过时了?

请帮忙。谢谢

标签: iosswift

解决方案


请注意,这篇文章来自 2014 年。

Article published date is Nov 19 2014

您使用的是旧版本:

将您的代码更新为此:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return toDoItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let item = toDoItems[indexPath.row]
    cell.textLabel?.text = item.text
    return cell
}

推荐阅读