ios - Swift NSUserDefaults unexpectedly found nil while unwrapping an Optional value -


//help please code won't work, getting feedback xcode. fatal error: unexpectedly found nil while unwrapping optional value


    var savedscore = nsuserdefaults.standarduserdefaults().objectforkey("highestscore") as! int 

import spritekit  class gamescene: skscene {      var highestscore:int = 2     var score = int()      override func didmovetoview(view: skview) {         /* setup scene here */          //to save highest score          //to saved score         var savedscore = nsuserdefaults.standarduserdefaults().objectforkey("highestscore") as! int          print(savedscore)       }      override func touchesbegan(touches: set<uitouch>, withevent event: uievent?) {        /* called when touch begins */         score += 1         print("score - \(score)")          if score > highestscore         {             highestscore = score             nsuserdefaults.standarduserdefaults().setobject(highestscore, forkey:"highestscore")             nsuserdefaults.standarduserdefaults().synchronize()             print("beat")         }          else {             print("not beat")         }      }      override func touchesmoved(touches: set<uitouch>, withevent event: uievent?) {      }      override func update(currenttime: cftimeinterval) {         /* called before each frame rendered */     } } 

you calling userdefaults function before ever saves. need check if exists. first can make easier on , save integer. need check see if there value.

nsuserdefaults.standarduserdefaults().setinteger(highestscore, forkey: "highestscore")  //integerforkey never return nil.  return 0 if there no value. let savedscore = nsuserdefaults.standarduserdefaults().integerforkey("highestscore")  print(savedscore) 

Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -