WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Project 12: Challenge 2 - Score save.

Forums > 100 Days of Swift

Hello, I'm trying to understand save data in my app using UserDefault, I'm trying both ways, Codable and NSCoding and it's not working. Right now I'm try to just use UserDefaults, but still nothing happend, in my breakpoint value of score are not coming to userdefaults, anyone know why?

import UIKit

class ViewController: UIViewController {

    @IBOutlet var button1: UIButton!
    @IBOutlet var button2: UIButton!
    @IBOutlet var button3: UIButton!

    var countries = [String]()
    var score = 0
    var correctAnswer = 0
    var counter = 0
    var wrongAnswer = " "
    let userDefaults = UserDefaults.standard

    override func viewDidLoad() {

        countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]
        button1.layer.borderWidth = 1
        button2.layer.borderWidth = 1
        button3.layer.borderWidth = 1

        button1.layer.borderColor = UIColor.lightGray.cgColor
        button2.layer.borderColor = UIColor.lightGray.cgColor
        button3.layer.borderColor = UIColor.lightGray.cgColor

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showScore))


        userDefaults.setValue(score, forKey: "score")
        let savedScore = userDefaults.data(forKey: "score")
    func askQuestion(action: UIAlertAction! = nil) {

        correctAnswer = Int.random(in: 0...2)
        button1.setImage(UIImage(named: countries[0]), for: .normal)
        button2.setImage(UIImage(named: countries[1]), for: .normal)
        button3.setImage(UIImage(named: countries[2]), for: .normal)

        counter += 1
        title = "\(countries[correctAnswer].uppercased()), Score is: \(score)"


    @IBAction func buttonTapped(_ sender: UIButton) {
        var title: String

        if sender.tag == correctAnswer {
            title = "Correct"
            score += 1
           // counter += 1
        } else {
            wrongAnswer = countries[sender.tag]
            title = "Wrong, thats a flag of \(wrongAnswer)"
            score -= 1
           // counter += 1

        let ac = UIAlertController(title: title, message: "Your score is \(score)", preferredStyle: .alert)

        if counter <= 10 {
            ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(ac, animated: true)

        }else {
        let at = UIAlertController(title: "10 guesses done", message: "You have reached the end of this game, your final Score is \(score)", preferredStyle: .alert)
                   at.addAction(UIAlertAction(title: "Restart", style: .default, handler: askQuestion))
                    present(at, animated: true)
            counter = 0
            score = 0


    @objc func showScore() {
        let showScore = UIAlertController(title: nil, message: "Your score is \(score)", preferredStyle: .alert)
        showScore.addAction(UIAlertAction(title: "Continue", style: .default, handler: nil))
        showScore.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
        present(showScore, animated: true)


I think with this line in viewDidLoad, you might be setting the saved score in your UserDefaults to 0 everytime you launch the app:

      userDefaults.setValue(score, forKey: "score")

I think you might have better luck using PropertyObservers here. Assuming you want to save the high score, something like this might work:

  var score = 0 {
      didSet {
        let savedScore = UserDefaults.standard.integer(forKey: "score") 
        if savedScore < score {
            UserDefaults.standard.setValue(score, forKey: "score")

Then in viewDidLoad, you can use something like:

        let savedScore = UserDefaults.standard.integer(forKey: "score")
        print("Saved Score: \(savedScore)")

The benefit of doing this is even if there is no key "score" in your user defaults, it will just return with a value of 0


Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.