将旧应用程序从swift 2.2更新为swift 4.我必须使用swift 3作为踏脚石。我转换为3但遇到以下错误:
二进制运算符'=='不能应用于'IndexPath'和'Int`类型的操作数
代码是:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath as NSIndexPath).row == 0 || indexPath == 1 {
self.performSegue(withIdentifier: "NFL", sender: self)
}
if (indexPath as NSIndexPath).row == 1 {
self.performSegue(withIdentifier: "AFL", sender: self)
}
if (indexPath as NSIndexPath).row == 2 {
self.performSegue(withIdentifier: "FAI", sender: self)
}
if (indexPath as NSIndexPath).row == 3 {
self.performSegue(withIdentifier: "IPA", sender: self)
}
}
为什么我在Swift 3而不是2.2中出现此错误?我试图强迫它进入“Int”,但不要以为我是以正确的方式进行的。
indexPath
包含row
和section
你需要指定你是否想要indexPath.row
或indexPath.section
如果你真的是指indexPath.row
,你的完整代码应如下所示:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 || indexPath.row == 1 {
self.performSegue(withIdentifier: "NFL", sender: self)
}
if indexPath.row == 1 {
self.performSegue(withIdentifier: "AFL", sender: self)
}
if indexPath.row == 2 {
self.performSegue(withIdentifier: "FAI", sender: self)
}
if indexPath.row == 3 {
self.performSegue(withIdentifier: "IPA", sender: self)
}
}
提示:
你不需要施放到NSIndexPath
为了进行比较,您应该使用switch
语句而不是许多if
statements。
如果indexPath.row == 1
它会以不同的结果执行两次。
Beacause indexPath返回Swift 4中的IndexPath
和返回(indexPath as NSIndexPath).row
的Int
,所以你不能强迫相等。你甚至不使用像indexPath as NSIndexPath
这样的indexpath。 indexPath.row
就足够了