Wang Nan Wang Nan - 2 months ago 13
iOS Question

Error: Found nil while unwrapping an Optional value; While Pass Data to the New Controller

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
}

}

Answer

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