Search code examples
swiftxcodeoption-typeuislideruserdefaults

Want to set Slidervalue to a UserDefault: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value


My problem is that I want to set the value of a slider to a UserDefault. In the first version of the app everything worked fine and I use the same code in version 2. Now Xcode shows the error "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value", but I never have used Optionals in the code. I have updated Xcode, maybe there is a problem.

Thank you in advance

func speichernNutzerEinstellungenIntervall(){
        standard.set(zeitInsgesamt, forKey: Keys.speichernZeitInsgesamt)
    }

func überprüfenLängeIntervall(){
    let speichernZeitInsgesamt = standard.integer(forKey: Keys.speichernZeitInsgesamt)

    zeitInsgesamt = speichernZeitInsgesamt 

    sliderIntervallOutlet.setValue(Float(zeitInsgesamt), animated: true) //Here I get the error}

(I have declared the variable "zeitInsgesamt" as a global variable. Don't know if this is important.)


Solution

  • The value of sliderIntervallOutlet is nil. Try to check nil value for property before set any value. Like this

    func überprüfenLängeIntervall(){
        let speichernZeitInsgesamt = standard.integer(forKey: Keys.speichernZeitInsgesamt)
    
        zeitInsgesamt = speichernZeitInsgesamt 
    
        if sliderIntervallOutlet != nil {
              sliderIntervallOutlet.setValue(Float(zeitInsgesamt), animated: true)
         }
    
    }