Creating a Singleton in Swift – The Nested Struct Approach

class AppService : BaseService {
    class var sharedInstance : AppService {
        struct Static {
            static let instance : AppService = AppService()
        return Static.instance

While refactoring one of my apps recently, I had to figure out how to create a singleton in Swift. This approach seems like the most widely accepted way. The shared instance is a class variable. A closure is used to initialize and return a static instance that is contained in the nested Static struct within the closure. Oodles of joy. This is called the nested struct approach. There are two more which can be seen here:

Leave a Reply

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