I am programming a board game. There are a couple of screen and many functions. I often need to change some variable like "money" or "wood". I added "didset" so I can update a View that displays the amount of money.
I see two options for this. Either a global variable
var money = 0 {didSet {NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showMoney"), object: nil)}}
or a singleton
class resources {
static let shared = resources()
var money = 0 {didSet {NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ResourcenAnzeigen"), object: nil)}}
private init() {}
}
Now I read singletons are always preferred instead of globals. But I wonder why. In my example both seem to do the same. The only difference is I either have to write
money += 1
or
resources.shared.money += 1
The first one looks easier.
And is there a third better way? I read one could give over the needed variables to every function or viewcontroller - but that looks to me like much unneccessary extra code?