Look at this:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var weightInput: UITextField!
@IBOutlet weak var heightInput: UITextField!
@IBOutlet weak var BMIOutput: UITextField!
@IBOutlet weak var categoryOutput: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.weightInput.delegate = self //added either ! or ? here and don't get fatal error
self.heightInput.delegate = self //added either ! or ? here and don't get fatal error
}
Line 2 you declare an IBOutlet, as implicitly unwrap.
That means that weightInput is an optional, so either nil or some value.
Implicitly unwrap means that if you call it once it has a value, you don't need to unwrap anymore. It is done implicitly.
But, if you call when it is not initialized (nil) and try to unwrap, of course you crash.
And an IBOutlet is loaded and initialized when the view is loaded. But the IBOulet var is initialized only if it is properly connected to the object in storyboard. Otherwise, no way to know which var to initilize, hence it remains nil.
So most likely in your case, the connection between th IBOutlet and the TextField in storyboard is not set or is broken.
Then, when you call line 10:
self.weightInput.delegate = self
Do you see a black dot on the left of
@IBOutlet weak var weightInput: UITextField!
If not, control drag from the white circle to the textField in storyboad.
The connection will be made, and crash will disappear (if you do it for all IBOutlets).
Note: you wrote:
The code builds in both cases and only produces a Fatal Error when I run the simulator without the unwrapping tags.
With the unwrapping added the simulator runs, but when I enter the data and click on the link nothing appears in the MY BMI text box.
It is logical not to crash with ?, but a bit surprising you do not crash with !
If weightInput is nil, when you set with optional chaining
self.weightInput?.delegate = self
in fact it does nothing (execution "halted" after ? because of nil).
TextField appear on screen, you can type, but delegate functions (as textFieldShouldReturn) are not called. Nothing appears in the MY BMI text