Created
September 17, 2015 17:59
-
-
Save cmoulton/a351f203b58f6efeea08 to your computer and use it in GitHub Desktop.
Start a counter at 10 and decrement when tapped (no lower than 0). Remembers value between runs of the app. https://www.reddit.com/r/swift/comments/3lbk2v/stuck_with_saving_a_number_and_decreasing_it_with/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
let clicksKey = "clicksKey" | |
let maxClicks = 10 | |
@IBOutlet weak var clicksLabel: UILabel! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
updateLabel() | |
} | |
func updateLabel() { | |
let clicks = getClicksRemaining() | |
if (clicks > 0) { | |
clicksLabel.text = "You have \(clicks) remaining" | |
} else { | |
clicksLabel.text = "You have no remaining" | |
} | |
} | |
func getClicksRemaining() -> Int { | |
let defaults = NSUserDefaults.standardUserDefaults() | |
// do we have a click count saved? | |
if defaults.objectForKey(clicksKey) != nil { | |
return defaults.integerForKey(clicksKey) | |
} else { | |
return maxClicks | |
} | |
} | |
@IBAction func tappedButton(sender: AnyObject) { | |
var currentCount = getClicksRemaining() | |
if (currentCount > 0) { | |
currentCount = currentCount - 1 | |
let defaults = NSUserDefaults.standardUserDefaults() | |
defaults.setInteger(currentCount, forKey: clicksKey) | |
updateLabel() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment