Search code examples
singletonswift3

Singleton with properties in Swift 3


In Apple's Using Swift with Cocoa and Objective-C document (updated for Swift 3) they give the following example of the Singleton pattern:

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()

        // setup code

        return instance
    }()
}

Let's imagine that this singleton needs to manage a variable array of Strings. How/where would I declare that property and ensure it gets initialized properly to an empty [String] array?


Solution

  • For me this is the best way, make init private. Swift 3 \ 4 \ 5 syntax

    // MARK: - Singleton
    
    final class Singleton {
    
        // Can't init is singleton
        private init() { }
    
        // MARK: Shared Instance
    
        static let shared = Singleton()
    
        // MARK: Local Variable
    
        var emptyStringArray = [String]()
    
    }