Swift realizes three ways of Singleton pattern in a singleton mode

Source: Internet
Author: User

Turn from: Click to open link

From my short experience with Swift there is three approaches to implement the Singleton pattern, support lazy Initia Lization and thread safety.

These approaches might change or become redundant as the language matures.

GLOBAL constant

Let _singletonsharedinstance = Singleton()

Class Singleton {

class var sharedinstance: Singleton {

return _singletonsharedinstance

}

}

We use a global constant because class constants is not yet supported.

This approach supports lazy initialization because Swift lazily initializes global constants (and variables), and is Threa D Safe by virtue of a let .

Nested struct

Class Singleton {

class var sharedinstance: Singleton {

struct Static {

Static Let instance: Singleton = Singleton ()

}

return static.instance

}

}

Unlike classes, structs do support static constants. By using a nested struct we can leverage its static constant as a class constant.

Dispatch_once

The traditional objective-c approach ported to Swift. I ' d say it ' s no longer necessary to use this approach but I ' m putting it's here anyway as I find the differences in syntax I Nteresting.

Class Singleton {

class var sharedinstance: Singleton {

struct Static {

Static var oncetoken: dispatch_once_t = 0

Static var instance: Singleton? = Nil

}

Dispatch_once (&static.oncetoken) {

static.instance = Singleton ()

}

return static.instance!

}

}

Swift realizes three ways of Singleton pattern in a singleton mode

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.