Understanding Singleton in Swift
I am trying to create a singleton in SWIFT and this is what I have done so far
class Global {
class var sharedInstance:Global {
struct singleton {
static let instance:Global = Global()
}
return singleton.instance
}
}
var a = Global.sharedInstance
var b = Global()
if a === b {
println("Pointing to Same Instance")
}
else {
println("Pointing to different instance")
}
I used the computed type property to create a singleton (found out that from another stack question). Currently the output is "Pointing to another instance".
What I'm looking for is "a" and "b" in the above example points to another instance of the GLOBAL class and that breaks the point of the singleton. How do "a" and "b" in the above example specify the same instance of the class.
thank
source to share
This pattern does not guarantee that there will be only one instance of the class Global
. It just allows any user to access one shared instance Global
through its property sharedinstance
.
So, it Global()
declares a new instance of the class Global
. But Global.sharedinstance
doesn't create a new instance Global
, just retrieves the previously created one (which is created the first time you access it).
(If you change the declaration b
to read var b = Global.sharedinstance
, you will see that it confirms, which is what a
they b
point to the same instance.)
If you want to prevent the creation of additional instances Global
, make it init
private:
private init() { }
But remember that you can still create another Globals
from the file it was declared in, so if you do this above in a playground or test project with a single file, you won't see any effect.
source to share
An instance of the class once in the life cycle of the application.
class AccountManager {
static var sharedInstance = AccountManager()
var userInfo = (ID:"Arjun",Password:"123")
private init(){
print("allocate AccountManager")
}
}
here we are setting Private, because:
Private access restricts the use of the object to the attached declaration and the extensions of that declaration, which are in the same file. Use private access to hide implementation details for a specific piece of functionality when those details are only used within a single declaration.
also set the static property sharedInstance
because if you need to access a property of a class without an instance of the class, you must declare "Static".
source to share