LoginSignup
6
6

More than 5 years have passed since last update.

Singleton in Swift

Last updated at Posted at 2016-09-23

What is Singleton?

Basically Singleton pattern is one of design pattern in object-oriented programming. Singleton class can have only one object. In other words, Singleton can keep an instance of class at a time. Normally, I use Singleton when app requires to globalized param.

If you would like to know how to implement Singleton in the best way, just take a look following content.

Using struct to define as static constant is most comfortable and genius way lol The reason that this method is useful is we can keep initiated instance in static constant. However, Xcode update made the code simpler. In this post, there are two code examples.

Depend on what you prefer

New

YourClassName.swift
class YourClassName {
    static var instance: YourClassName = YourClassName()
    private init() {
    }
}

Old

YourClassName.swift
class YourClassName {
    class var sharedInstance : YourClassName {
        struct Singleton {
            static let instance : YourClassName = YourClassName()
        }
        return Singleton.instance
    }
}

References

6
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6