Amen Parham Amen Parham - 7 months ago 31
Swift Question

Swift NSUserDefaults unexpectedly found nil while unwrapping an Optional value

//Help Please This Code won't work, getting this as feedback from Xcode.
fatal error: unexpectedly found nil while unwrapping an 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 your scene here */

//To save highest score

//To get the saved score
var savedScore = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as! Int

print(savedScore)


}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a 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 is rendered */
}
}

Answer

You are calling the userDefaults function before it ever saves. You need to check if it exists. First you can make it easier on yourself and just save it as an integer. Then you need to check to see if there is a value.

NSUserDefaults.standardUserDefaults.setInteger(highestScore, forKey: "HighestScore")



if let savedScore = NSUserDefaults.standardUserDefaults.integerForKey("HighestScore") {
       print(savedScore)
}