Issues Running the 'Implemeting the Temperature Conversion' Section


#1

After adding the code on pages 79, 80, and 81, my application has failed to run properly (and it was running properly before this). My code is exactly the same as the book, I have checked and rewritten it multiple times. It will load the white screen, and then open the debugger with a statement that says, “fatal error: unexpectedly found nil while unwrapping an optional value”. Any ideas on what I may be doing wrong and what I can do to fix it?? All answers appreciated.

The code of my View Controller reads as following:


import UIKit

class ConversionViewController: UIViewController {
    
    @IBOutlet var celsiusLabel: UILabel!
    var fahrenheitValue: Measurement<UnitTemperature>? {
        didSet {
            updateCelsiusLabel()
        }
    }
    
    var celsiusValue: Measurement<UnitTemperature>? {
        if let fahrenheitValue = fahrenheitValue {
            return fahrenheitValue.converted(to: .celsius)
        } else {
            return nil 
        }
    }
    // Add this func to tell the celsius label to update every time the fahr value changes
    func updateCelsiusLabel() {
        if let celsiusValue = celsiusValue {
            celsiusLabel.text = "\(celsiusValue.value)"
        } else {
            celsiusLabel.text = "???"
        }
    }
    
    /////////
    
    @IBOutlet var  textField:UITextField!
    
    @IBAction func fahrenheitFieldEditingChanged(_ textField: UITextField) {
        
        if let text = textField.text, let value = Double(text) {
            fahrenheitValue = Measurement(value: value, unit: .fahrenheit)
        } else {
            fahrenheitValue = nil
        }
    }
    
    
    // override  the viewDidLoad() function to set the initial value 
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        updateCelsiusLabel()
    }
    
    /////////////////////
    
    @IBAction func dismissKeyboard(_ sender: UITapGestureRecognizer) {
        textField.resignFirstResponder()
    }
}


#2

You are trying to access an uninitialised (optional) property.

However, from the information you have provided, it is impossible to diagnose the problem remotely. You should always post enough code to make it possible for others to see your code. Also you should make sure that the posted code is properly formatted. If you don’t know already, read this post to learn How to Post Code Properly Formatted.


#3

Thank you for the tips, I’m new to this so not 100% sure what to include. So far I have updated it to include my code, thanks


#4

Ok, that’s much better now.

I can see that you have an implicitly-unwrapped optional property named celsiusLabel:

...
class ConversionViewController: UIViewController {
    
    @IBOutlet var celsiusLabel: UILabel!
    ...
}

Make sure that you bind that property to the corresponding UILabel object in interface builder, by following the instructions in the book.