Necro1992 Necro1992 - 1 year ago 119
iOS Question

Xcode 8 - unexpectedly found nil

I just started learning swift and i have a question.
I have two view controllers, and i'm trying to send a string from view 1 to view 2.

This is what i've got so far:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
if segue.identifier =="1"
let DestViewControl = segue.destination as! ViewController2
DestViewController.count = 9

Count is a variable in view 2. So far this works great.
However, if i want to automatically change the text in a label in view 2, as DestViewController.lb_ExLabem.text = "test" , i get a fatal error "unexpectedly found nil while unwrapping an optional value".

Let me know if you have any ideas.


Answer Source

Before the segue, you outlet is nil (since the view is not loaded).

In DestViewController, you should create a variable to store the text:

class ViewController2{
    @IBOutlet weak var your_label: UILabel!
    var label_tex=String()

Initiate it in prepareForSegue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?){
    if segue.identifier =="1"{
        let DestViewControl=segue.destination as! ViewController2

And finally in ViewController2, change your label text when the view is loaded (and your outlet not nil anymore):

override func viewWillAppear(_ animated: Bool){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download