Jeenal Infotech

How to create singleton class in swift?

In my previous post we have learnt about what is singleton pattern and the right way to implement them in Objective-C.

Here we will discuss how to achieve the same singleton pattern in Swift.

In Swift, there are multiple ways to achieve singleton pattern. If you are using swift 1.2 or above then use the class constant approach as mentioned below.

CLASS CONSTANT APPROACH: (For Swift 1.2 and above)

class Utility {
    static let sharedInstance = Utility()
private init() {}  // private initializer of the class will restrict others from using the default initializer.
}

But if you are still supporting previous versions then nested struct approach needs to be followed.

NESTED STRUCT APPROACH: (For Swift 1.0 and 1.1)

class Utility {
    class var sharedInstance: Utility {
        struct Static {
            static let instance: Utility = Utility()
        }
        return Static.instance
    }
}
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkedin
Contact us

2 thoughts on “How to create singleton class in swift?

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons