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
}
}
In another class(UIViewcontroller
) I would like to use it,
Globals.sharedInstance //is going ok
is good, but when i go deep to .max
i get the error.
You can't just have var = xxx
in an init. The variable has to be declared at the class top level.
Example of using your singleton:
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With