I am building a swift game and a need to set up a highscore , i have been trying to figure out how to do it for a while. So please can you tell me how to search this library to see if there is a already saved high score and then compare it to the user's score. I have tried coming out with this but it won't work. Please Help and be as clear as possible. Giving me example code would be extremely appreciated.
if let highscore: AnyObject = NSUserDefaults.valueForKey("highscore") { var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("highScore") as Int if ( savedScore < Score) { var highscore = Score NSUserDefaults.standardUserDefaults().setObject(highscore, forKey:"highscore") NSUserDefaults.standardUserDefaults().synchronize() } } else { var highscore = Score NSUserDefaults.standardUserDefaults().setObject(highscore, forKey:"highscore") NSUserDefaults.standardUserDefaults().synchronize() }
Create a new iOS project in Xcode by using the Single View Application template. Then, replace the content of ViewController.swift
with the following code:
import UIKit class ViewController: UIViewController { var generator = [6, 12, 8].generate() override func viewDidLoad() { super.viewDidLoad() let button = UIButton(type: .System) button.setTitle("Button", forState: .Normal) button.addTarget(self, action: "newScore", forControlEvents: .TouchUpInside) button.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) // Auto layout code using anchors (requires iOS9+) let horizontalConstraint = button.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor) let verticalConstraint = button.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor) NSLayoutConstraint.activateConstraints([horizontalConstraint, verticalConstraint]) // Print NSUserDefaults's highscore value when app is launched print("highscore:", NSUserDefaults.standardUserDefaults().integerForKey("highscore")) } func newScore() { guard let score = generator.next() else { return } print("current score:", score) //Check if score is higher than NSUserDefaults stored value and change NSUserDefaults stored value if it's true if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") { NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore") NSUserDefaults.standardUserDefaults().synchronize() } print("highscore:", NSUserDefaults.standardUserDefaults().integerForKey("highscore")) } }
Build and run the project on your iPhone or on the simulator. The Xcode console will print 0, which is the current value for NSUserDefaults.standardUserDefaults().integerForKey("highscore")
.
Now, click on the button. This will set the value of score
to 6
and, because 6 > 0
, NSUserDefaults.standardUserDefaults().integerForKey("highscore")
will get this new value.
Click once again on the button. This will set the value of score
to 12
. You will immediately see in the console that NSUserDefaults.standardUserDefaults().integerForKey("highscore")
gets this new value.
Now, if you change the value of score
to 8
by clicking on the button, you will see that NSUserDefaults.standardUserDefaults().integerForKey("highscore")
still has a value of 12
because 8 < 12
.
If you rebuild your project and relaunch it, you will see that NSUserDefaults.standardUserDefaults().integerForKey("highscore")
is persistent (its value is still 12 and has not been reset). Therefore, NSUserDefaults
can be a perfect tool in order to store your players highest scores.
Extra tip
NSUserDefaults.standardUserDefaults().integerForKey("highscore")
always return an Int
(if you haven't set it by yourself, it will return 0
, not nil
). Thus, you dont need to / can't use optional binding with it. If you really want to deal with an optional value return, you will prefer NSUserDefaults.standardUserDefaults().objectForKey("highscore") as? Int
.
var defaults=NSUserDefaults() var highscore=defaults.integerForKey("highscore") if(Score>highscore) { defaults.setInteger(Score, forKey: "highscore") } var highscoreshow=defaults.integerForKey("highscore") lblHighScore.text="\(highscoreshow)" println("hhScore reported: \(lblHighScore.text)") lblPlayScore.text="\(Score)" println("play reported: \(lblPlayScore.text)")