Wang Nan Wang Nan - 1 year ago 83
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)




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


Answer Source

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


var strValue:String?

func viewDidLoad(){

   label.text = strValue!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download