HiveBrain v1.2.0
Get Started
← Back to all entries
patternswiftMajor

Swift 1.2 Singleton Implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
swiftimplementationsingleton

Problem

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() -> 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

Solution

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()

Code Snippets

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
    }
}
FGSingleton.sharedInstance.displayGameScore()

Context

StackExchange Code Review Q#80246, answer score: 25

Revisions (0)

No revisions yet.