Richa Goyal
Richa Goyal

Reputation: 23

Passing values from one view controller to another in Swift

I am working on Swift, I've got an error in tableview's didSelectRowAtIndexPath method. I want to pass a value to another view controller i.e 'secondViewController'. Here EmployeesId is an Array. The relevant code is as follows:

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.
}

But I am getting this Error: fatal error: unexpectedly found nil while unwrapping an Optional value.

Any help will be appreciated.

Upvotes: 1

Views: 24719

Answers (3)

Ron Fessler
Ron Fessler

Reputation: 2789

Here's a general solution with two assumptions. First, UserId is not a UILabel. Second, you meant to use view which was instantiated in the second line, instead of using secondViewController

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard
    view.userId = employeesId[indexPath.row]
    self.navigationController?.pushViewController(view, animated: true)
    
}

Here's what Dashboard looks like:

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
    }

    ...
}

Upvotes: 8

Enamul Haque
Enamul Haque

Reputation: 5053

We can pass value using "struct" in swift 3

  1. Create a swift file in your project
  2. Create a class in the swift file created like bellow

        class StructOperation {
          struct glovalVariable {
          static var userName = String();
         }
     }
    
  3. Assing value to "static var userName" variable of " struct glovalVariable" in "StructOperation" class from First View Controller like

     @IBAction func btnSend(_ sender: Any) {
        StructOperation.glovalVariable.userName = "Enamul Haque";
       //Code Move to Sencon View Controller
     }
    
  4. In destination view controller get value like bellow

     var username = StructOperation.glovalVariable.userName;
    

Upvotes: 4

casillas
casillas

Reputation: 16793

is UserId(strong, nonatomic) in the secondViewController?

If it is weak, it sent trash on the fly. You have to make it strong.

Upvotes: 0

Related Questions