I'm new at Xcode and currently making an app, where you have an amount of "bananas / money", whereof you can flip a coin, and you either win 2x or lose your bet. (Just for experience)
My game is fully working, I've now just decided, that I want to save the currency for whenever the app closes and starts; using NSUserDefaults.
I've set my NSUserDefaults up, and it's working. It's displaying the currency I had the last time I closed the app, and I can only bet between 0 and my currency. - Which is great!
However, even though my full currency is displaying, and that I can bet all of my total currency, the math behind it all is still struggling. After the app closes it's putting the integer back to 0, because that's what I've declared ABOVE my viewDidLoad, when I was creating the variable.
Haven't understood? Lets say I have 30 bananas, and I'm about to bet 30 bananas. If I win, I'll have a total of 30 banans, and if I lose, I'll have -30 bananas. (The integer is for some reason set to 0)
I need a way to set the integer to my last saved; "currencySave". - And I need a way of detecting if it's the first time the app has been opened; if yes, you'll have to start with a constant integer/currency.
Code:
All of my variables are ment to be in integers.
betVar; the variable / value, that you're betting
currencyVar; the variable / value, that you're having. (Your cash)
currencySave; the name I've saved my integer into
Above viewDidLoad
let defaults = UserDefaults.standard
var currencyVar = Int(0)
var betVar = Int(0)
viewDidLoad
let currencyVar = defaults.integer(forKey: "currencySave")
labelCurrency.text = String("$ \(currencyVar)")
betVar = 0
labelBet.text = String("$ \(betVar)")
Slider, whereof you choose the bet-amount
let currencyVar = defaults.integer(forKey: "currencySave")
let currentValue:String = String(Int(sender.value))
betVar = Int(currentValue)!
labelBet.text = currentValue
labelSlider.maximumValue = Float(currencyVar)
labelSlider.minimumValue = Float(0)
labelBet.text = String("$ \(currentValue)")
The math when winning a bet (It takes the money from you as you click 'bet', that means, that nothing will happen, if you're losing.)
self.currencyVar = self.currencyVar + self.betVar*2
self.labelBet.text = String("\(self.betVar*2)")
self.labelBet.textColor = UIColor.green
My way of saving the integer
defaults.set(currencyVar, forKey: "currencySave")
defaults.synchronize()