Swift-Implementation of a singleton pattern

Source: Internet
Author: User

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 vara1 = AppManager() //确保编译不通过vara2 = AppManager() //确保编译不通过

Swift-Implementation of a singleton pattern

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.