转换为Swift 3时出现UITableView错误

问题描述 投票:-4回答:2

将旧应用程序从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”,但不要以为我是以正确的方式进行的。

swift uitableview swift3 swift2
2个回答
2
投票

indexPath包含rowsection

你需要指定你是否想要indexPath.rowindexPath.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语句而不是许多ifstatements。

如果indexPath.row == 1它会以不同的结果执行两次。


1
投票

Beacause indexPath返回Swift 4中的IndexPath和返回(indexPath as NSIndexPath).rowInt,所以你不能强迫相等。你甚至不使用像indexPath as NSIndexPath这样的indexpath。 indexPath.row就足够了

© www.soinside.com 2019 - 2024. All rights reserved.