可选类型的值'NSIndexPath?'未解开包装;你的意思是使用'!'还是"?"?



我在代码上有一个问题,我认为我将语法更改为新的swift版本后出现的问题。

import UIKit
class FirstTableViewController: UITableViewController {
    var FirstTableArray = [String]()
    var passThisArray = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        // This array will display on your tableviewcell.
        FirstTableArray = [lib1]
        //You can pass element of this array
        passThisArray = ["1. Fi "]
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return FirstTableArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let Cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
        Cell.textLabel?.text = passThisArray[(indexPath as NSIndexPath).row]
        return Cell
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "detailView") {
            let vc = segue.destination as! ViewController
            //Get the Index of selected Cell
            let indexPath : IndexPath = self.tableView.indexPathForSelectedRow!
            //assign string to next view controller instance from selected cell.
            vc.FirstString = FirstTableArray[(indexPath as NSIndexPath).row]
        }
    }
}

在这条线上给我2个错误:

let indexPath : IndexPath = self.tableView.indexPathForSelectedRow!
  1. 可选类型的" nsindexpath?"的值没有包装;你是说 使用 '!'或'?'?

  2. 无效使用'()'调用非功能类型的值 'nsindexpath?'

谢谢。

问题是不能保证用户选择了一行,因此您对indexPathForSelectedRow的调用是可选的(它可能具有或可能没有值)。

改进此方法的一种方法是使用Guard语句安全解开您在此方法中拥有的两个可选值。如果没有设置其中一个(nil),则该方法将安全退出而不会崩溃。

if let ...方法上使用后卫的一个好处是,您可以避免厄运金字塔。使用您的示例,将需要三个凹痕运行分配字符串的最终命令,从而使您的代码更难读取。警卫声明明确说"如果此值失败,请防止撞车"。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if(segue.identifier == "detailView") {
        guard let vc = segue.destination as? ViewController else {
            return
        }
        //Get the Index of selected Cell
        guard let indexPath = self.tableView.indexPathForSelectedRow else {
            return
        }
        //assign string to next view controller instance from selected cell.
        vc.FirstString = FirstTableArray[(indexPath as NSIndexPath).row]
    }
}

另外,两个次要的代码样式沉思:

  • 分配给indexPath时,您不需要使用:NSINDEXPATH。编译器可以推断您的类型
  • 在声明变量时,iOS惯例是使用骆驼,因此,虽然您的IndexPath变量不错,但您应该将FirstString更改为firstString

相关内容

最新更新