ios - 出现此错误的原因是什么:“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 部分
会不会是有些东西过时了?
请帮忙。谢谢
解决方案
请注意,这篇文章来自 2014 年。
您使用的是旧版本:
tableView(_:numberOfRowsInSection:)
tableView(_:cellForRowAt:)
dequeueReusableCell(withIdentifier:for:)
将您的代码更新为此:
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
}
推荐阅读
- html - 停用html模板中的按钮和分类功能
- vue.js - 如何在 Nuxt.js 的 Vuex 存储中使用异步获取?
- scala - Akka Play guice 绑定无标签最终(TF)支持
- javascript - 发现重复键时如何更新 MongoDB 文档的值?
- r - 无法在 R 中使用“lrm.fit”拟合模型
- java - 将 Liquibase 迁移应用于多模块 gradle 项目的集成测试
- javascript - 如何通过jQuery从字符串中删除多余的空格并且只计算实际的字符数?
- r - 如何在 Shiny 中选择行和列并使用 DT 进行过滤?
- php - Laravel php 检查会议是否已安排
- python - 如何使用 Python Bokeh 库制作事件图?