Trouble with Optionals..Help Needed

Somewhat new to Swift. I am working on a sample Swift project and getting the following error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

I understand that Optionals mean that a field can or cannot have a value. I have posted the sample code I am working on, I thought I declared the optional correctly but I must be missing something, can someone provide a little insight as to what I am missing.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) {
    
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    segue.destination.navigationItem.title = textField!.text

    
}

}

The exclamation mark means you know the optional must have a value, so you want to ignore the possibility of it being absent. If you are wrong, then the program will crash, and the message you will get in debug mode is exactly what you are seeing. The exclamation mark is for cases like this:

if array.isEmpty {
    print("The array is empty.")
} else {
    print(array.first!)
    // Since we know that the array has some elements in it,
    // we also know one of them must be first.
}

But under most circumstances you want to do something that handles both possibilities:

if let firstElement = array.first {
    print(firstElement)
    // This checks whether there actually is a first element
    // before trying to use it.
} else {
    print("There is no first element, so the array must be empty.")
}

In the following line, you promised the compiler that textField would have a value, but when the program got there, it discovered there really wasn’t.

segue.destination.navigationItem.title = textField!.text

You will need to do something somewhere to provide a value before the program reaches that point. This modification would at least prevent the crash:

if let text = textField?.text {
    segue.destination.navigationItem.title = text
} else {
    print("There is no text field.")
}

Given that it is an @IBOutlet, the root issue is probably that it has no value because it is not connected to anything in your nib file.

I would do it like this:

segue.destination.navigationItem.title = textField?.text ?? ""

if textField is nil, title will be set as "".

Thank you so much for your help. And apologies for the delayed response to your solution.

I appreciate your help.

Larry

Terms of Service

Privacy Policy

Cookie Policy