Swift 1.2 Singleton Implementation I am pretty new to Swift, as a solo developer I was wondering if somebody could pass comments on the singleton implementation below. The code does work, but being new to Swift and knowing that there are a lot of gotchas, I wanted to get some feedback from someone more experienced.

// Test Singleton Swift 1.2
class FGSingleton {
    static var instance: FGSingleton!
    var gameScore: Int = 0

    // SHARED INSTANCE
    class func sharedInstance() -&gt; FGSingleton {
        self.instance = (self.instance ?? FGSingleton())
        return self.instance
    }

    // METHODS
    init() {
        println(__FUNCTION__)
    }
    func displayGameScore() {
        println("\(__FUNCTION__) \(self.gameScore)")
    }
    func incrementGameScore(scoreInc: Int) {
        self.gameScore += scoreInc
    }
}


Tests:

FGSingleton.sharedInstance().displayGameScore()
FGSingleton.sharedInstance().incrementGameScore(100)
FGSingleton.sharedInstance().incrementGameScore(1)
FGSingleton.sharedInstance().displayGameScore()
FGSingleton.sharedInstance().incrementGameScore(1000)
FGSingleton.sharedInstance().displayGameScore()


Output:


init()
displayGameScore() 0
displayGameScore() 101
displayGameScore() 1101
You could simplify the above significantly:

class FGSingleton {
    static let sharedInstance = FGSingleton()

    var gameScore: Int = 0

    // METHODS
    private init() {
        println(__FUNCTION__)
    }
    func displayGameScore() {
        println("\(__FUNCTION__) \(self.gameScore)")
    }
    func incrementGameScore(scoreInc: Int) {
        self.gameScore += scoreInc
    }
}


And call it like this:

FGSingleton.sharedInstance.displayGameScore()