1

I'm learning swift 2. I'm trying to pass the data of the cell (UITableView) that is tapped to the new View Controller. But I constantly get the error of: "unexpectedly found nil while unwrapping an Optional value" for the code line "destination!.label.text = valueToPass".
Below is my code.
May I know what should I do to solve it? I have spent hours but still stuck with it.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let indexPath = tableView.indexPathForSelectedRow;
     let Mycell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

     valueToPass = (Mycell.textLabel?.text)!
     performSegueWithIdentifier("webNext", sender: self)

        print("\(indexPath!.row)")

        print(valueToPass)

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "webNext") {
        let destination = segue.destinationViewController as? web___ViewController
        destination!.label.text = valueToPass
    }

}
Bista
  • 7,869
  • 3
  • 27
  • 55
Wang Nan
  • 15
  • 3
  • The `destination!` is causing the issue. You don't have a `destination` ViewController. Try `if let destination = segue.destinationViewController as? web___ViewController { }`. Inside that block the `destination` will not be `nil` – Sachin Vas Oct 06 '16 at 04:37
  • 1
    Two suggestions for *learning*: 1) Get use to the naming convention – variables and methods / functions start with a lowercase letter, classes, structs and enums start with a uppercase letter and without underscores. 2) **Never** get data from the table view cell (the view), get it from the data source array (the model) – vadian Oct 06 '16 at 04:42

1 Answers1

3

By doing this: destination!.label.text = valueToPass, you are already setting some text to the label before even it is drawn or presented.

Rather use some variable to pass data to next view and show that data inside viewDidLoad.

let destination = segue.destinationViewController as? web___ViewController

destination!.strValue = valueToPass

Web_VC:

var strValue:String?

func viewDidLoad(){
   super.viewDidLoad()

   label.text = strValue!
}
Bista
  • 7,869
  • 3
  • 27
  • 55