Search code examples
swift3intxcode8userdefaults

Adding a integer to your overall score every time you get a score


In my app you have to complete a couple questions and you are timed. At the end of the quiz you are given a score, which is a Int. I have passed that through to the main menu and my overall score displays the score i just got. I would like to know how when ever a new score is earned by the user, that the new score adds onto the overall score. My overallScore label displays my score and intPassed is the integer that is passed to the view controller. Then it would save permanently using User defaults. Any ideas on how to do this?


Solution

  • // Get, add
    var oldScore = UserDefaults.standard.integer(forKey: "overallScore")
    var newScore = oldScore + intPassed
    
    // Save
    UserDefaults.standard.set(newScore, forKey: "overallScore")
    
    // Display
    overallScore.text = String(newScore)