In the past, Swift was trying to implement a singleton, which was nothing more than three ways: global variables, internal variables, and Dispatch_once methods. But it's a little cumbersome.
Later, from version 1.2, Swift has addedThe support of class variables such as static let and static Var, which simplifies the implementation of a single example.
Here are two good examples of a single example. (Note that the init () method is privatized regardless of the notation.) Because the constructors for all objects are public by default in Swift, you need to rewrite init to make it private, preventing other objects from using the default ' () ' initialization method of the class to create the object. Thanks for the reminder of the Netizen nowisfuture here. )
Method 1:
123456789101112 |
class AppManager {
private static let _sharedInstance =
AppManager
()
class func getSharedInstance() ->
AppManager {
return _sharedInstance
}
private init
() {}
// 私有化init方法
}
//使用方式
AppManager
.getSharedInstance()
|
Method 2:
12345678 |
class appmanager { static let sharedinstance = appmanager ()      private init () {} //privatization init method } //How to use appmanager .sharedinstance |
Attached: Why do I need to guarantee the privatization of INIT?
Because only init () is private, you can prevent other objects from creating the class object directly from the default constructor, ensuring that your singleton is truly unique. Because the constructors for all objects are public by default in Swift, you need to rewrite your init to make it private. This will ensure that code such as the following compile error, cannot pass.
12 |
var a1 = AppManager () //确保编译不通过 var a2 = AppManager () //确保编译不通过 |
Swift-Implementation of a singleton pattern