0
import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var textFiled: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func pressDoneButton(_ sender: UIBarButtonItem) {
        performSegue(withIdentifier: "showSecondVC", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showSecondVC" {
            let secondVC = segue.destination as! SecondViewController
            secondVC.textLabel.text = textFiled.text!
        }
    }

}

The error is : thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

But I'm sure textFiled.text! contains a value.

Why the error comes?

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165

1 Answers1

0

You are trying to do,

secondVC.textLabel.text = textFiled.text!

You are right about textFiled.text! does have value and it is not nil here. But secondVC.textLabel is nil because secondVC is not loaded yet and all the outlets of a view-controller will be nil before it loads.

You should pass textFiled.text! to some variable and assign this to text-field in viewDidLoad method of SecondViewController.

Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36