Swift 3 将单元格数据 A 视图传递到 B 视图,有趣的 didSelectRowAt indexPath 在 select 行后崩溃

Swift 3 pass the cell data A view to B view, with fun didSelectRowAt indexPath crash after select row

我想将数据A视图传递给B视图,它可以在A视图中构建和显示数据,但是在我选择单元格后,它崩溃了。它在代码上显示了问题。

vcTwo.selectedzones.zones = [selectedCity]

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

我的代码

结构模式:

struct Location {
    var city: String!
    var zones = [String]()
}
var city = ["KHT", "TPAP", "TNNY"]

let kh = Location.init(city: "KHT", zones: ["sami", "zami", "zomi", "komi", "shini"])
let tpa = Location.init(city: "TPAP", zones: ["mid", "east", "anci", "zochi"])
let tnn = Location.init(city: "TNNY", zones: ["TN1","TN2", "TN3", "TN4", "TN5"])

这里是AviewController代码:

    import UIKit

class FirstViewTableViewController: UITableViewController {

   override func viewDidLoad() {
        super.viewDidLoad()
  }

   // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return city.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FirstCell

          cell.firstLabel.text = city[indexPath.row]

          return cell
    }



    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


        let selectedCity = city[indexPath.row]
        let vcTwo = self.storyboard?.instantiateViewController(withIdentifier: "secondVC") as! secondViewController
         vcTwo.selectedzones.zones = [selectedCity]

        self.navigationController?.pushViewController(vcTwo, animated: true)

    }
 }

乙viewController:

import UIKit

class secondViewController: UITableViewController {

    var selectedzones: Location!


    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return selectedzones.zones.count
    }

func didSelectRowAt indexPath 是不是哪里有问题?

试试这个

class secondViewController: UITableViewController {

    var selectedzones = Location()
}

您正在尝试访问 zones,但您尚未分配 Location,因此它会崩溃。 希望对您有所帮助

问题来了

     vcTwo.selectedzones.zones = [selectedCity]

您需要在第一个 Controller 中初始化 selectedZone

     let kh = Location.init(city: "KHT", zones: ["sami", "zami", "zomi", "komi", "shini"])

     vcTwo.selectedzones = kh

而不是可选的!使用可选的?

class secondViewController: UITableViewController {
var selectedzones: Location?

NOT 

class secondViewController: UITableViewController {
var selectedzones: Location!