0

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.)

Lukas
  • 251
  • 2
  • 13

1 Answers1

0

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)
     }

}
Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
  • Thanks, but now I get the Error: "Initializer for conditional binding must have Optional type, not 'Int' " in the line with "if let speichernZeitInsgedamt....". Do you know how to fix that? I can't change speichernZeitInsgesamt to an optional, can I? – Lukas Apr 07 '20 at 11:04
  • What is the value of `standard.integer(forKey: Keys.speichernZeitInsgesamt)`? is it returning any value? – Faysal Ahmed Apr 07 '20 at 11:05
  • Yes, I print it and it says "163". But when I want to set the value of the slider to the value of speichernZeitInsgesamt I get the error. – Lukas Apr 07 '20 at 11:14
  • What is `sliderIntervallOutlet`? please check this is nil or not. – Faysal Ahmed Apr 07 '20 at 11:18
  • Yes, the value of sliderIntervallOutlet is nil. But why is that a problem? – Lukas Apr 07 '20 at 11:22
  • sliderIntervallOutlet is not initialise or before initialization you try to put value on this. Or you can check the property is connected with Storyboard or not. – Faysal Ahmed Apr 07 '20 at 11:31
  • Thanks, I solved it with an if-statment: if sliderIntervallOutlet != nil. By the second the start of the app the slider value was set to the Userdefault-value. – Lukas Apr 07 '20 at 11:40