问题描述
我创建了一个新文件 ->swift file
.称为 Globals.Swift
然后在那里我做了:
I have created a new file ->swift file
. called Globals.Swift
Then in there I have done :
class Globals {
static let sharedInstance = Globals()
init() {
var max=100
}
}
在另一个类(UIViewcontroller
)中,我想使用它,
In another class(UIViewcontroller
) I would like to use it,
Globals.sharedInstance //is going ok
很好,但是当我深入到 .max
时,我得到了错误.
is good, but when i go deep to .max
i get the error.
推荐答案
你不能在 init 中只使用 var = xxx
.变量必须在类顶层声明.
You can't just have var = xxx
in an init. The variable has to be declared at the class top level.
使用单身人士的例子:
class Globals {
static let sharedInstance = Globals()
var max: Int
private init() {
self.max = 100
}
}
let singleton = Globals.sharedInstance
print(singleton.max) // 100
singleton.max = 42
print(singleton.max) // 42
当你需要在另一个类中使用单例时,你只需在另一个类中这样做:
When you need to use the singleton in another class, you just do this in the other class:
let otherReferenceToTheSameSingleton = Globals.sharedInstance
根据 Martin R 和 Caleb 的评论进行更新: 我已将初始化程序设为私有.在其他 Swift 文件中,它阻止了 Globals()
的初始化,通过只能使用 Globals.sharedInstance
来强制此类作为单例行为.
Update following Martin R and Caleb's comments: I've made the initializer private. It prevents, in other Swift files, the initialization of Globals()
, enforcing this class to behave as a singleton by only being able to use Globals.sharedInstance
.
这篇关于很难在 swift 中实现一个简单的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!