Skip to content

Instantly share code, notes, and snippets.

@cmoulton
Created September 17, 2015 17:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmoulton/a351f203b58f6efeea08 to your computer and use it in GitHub Desktop.
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/
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