And*_*ndy 2 variables singleton global ios swift
我正在编写棋盘游戏。有几个屏幕和许多功能。我经常需要改变一些变量,比如“钱”或“木头”。我添加了“didset”,所以我可以更新一个显示金额的视图。
我看到了两个选项。要么是全局变量
var money = 0 {didSet {NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showMoney"), object: nil)}}
Run Code Online (Sandbox Code Playgroud)
或单身人士
class resources {
static let shared = resources()
var money = 0 {didSet {NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ResourcenAnzeigen"), object: nil)}}
private init() {}
}
Run Code Online (Sandbox Code Playgroud)
现在我读到单例总是首选而不是全局变量。但我想知道为什么。在我的例子中,两者似乎都做同样的事情。唯一的区别是我要么必须写
money += 1
Run Code Online (Sandbox Code Playgroud)
或者
resources.shared.money += 1
Run Code Online (Sandbox Code Playgroud)
第一个看起来更容易。
还有第三种更好的方法吗?我读过一个可以将所需的变量交给每个函数或视图控制器 - 但这在我看来就像很多不必要的额外代码?
| 归档时间: |
|
| 查看次数: |
1069 次 |
| 最近记录: |