iosswiftoption-typeuifontforced-unwrapping

Why am I getting a "Value of optional type UIFont not unwrapped", but unwrapping gives "unexpectedly found nil while unwrapping an optional"?


func initializePickerViewProperties() {
    let font = UIFont (name: "SanFranciscoDisplay-Regular", size: 30.0)
    let highlightedFont = UIFont (name: "SanFranciscoDisplay-Bold", size: 35.0)
    pickerView.font = font!
    pickerView.highlightedFont = highlightedFont!
}

fairly simple, the pickerView in question is an AKPickerView

If I remove the forced unwrapping I get a compiler error. "Value of optional type UIFont not unwrapped, did you mean to use "!" or "?"?"

However, when I force unwrap it, I get a runtime error. "fatal error: unexpectedly found nil while unwrapping an Optional value"


Solution

  • Means your fonts are not initialized properly and give nil. You should safely unwrap them:

    func initializePickerViewProperties() {
        if let font = UIFont (name: "SanFranciscoDisplay-Regular", size: 30.0),
            let highlightedFont = UIFont (name: "SanFranciscoDisplay-Bold", size: 35.0) {
            pickerView.font = font
            pickerView.highlightedFont = highlightedFont
        }
    }