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.