在Swift中将值从一个视图控制器传递到另一个视图控制器

Ric*_*yal 2 ios swift

我正在研究Swift,我在tableview的didSelectRowAtIndexPath方法中遇到了错误.我想将值传递给另一个视图控制器,即'secondViewController'.这里EmployeesId是一个数组.相关代码如下:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard

    self.navigationController?.pushViewController(view, animated: true)
    secondViewController.UserId = employeesId[indexPath.item]  //getting an error here.
}
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:致命错误:在展开Optional值时意外发现nil.

任何帮助将不胜感激.

Ron*_*ler 6

这是一个有两个假设的通用解决方案.首先,UserId不是UILabel.其次,你打算使用view在第二行中实例化的,而不是使用secondViewController

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard

    self.navigationController?.pushViewController(view, animated: true)
    view.UserId = employeesId[indexPath.row]
}
Run Code Online (Sandbox Code Playgroud)

这是仪表板的样子:

class Dashboard: UIViewController {
    var UserId: String!
    @IBOutlet var userIDLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        userIDLabel.text = UserId
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)