Ios 在Swift 2.1中使用单例

Ios 在Swift 2.1中使用单例,ios,swift,Ios,Swift,我编写这个示例类是为了测试Swift 2.1中的Singleton: class FGSingleton { static let sharedInstance = FGSingleton() var gameScore: Int = 0 let path = NSBundle.mainBundle().pathForResource("Data", ofType: "plist") //below line is creating issue because

我编写这个示例类是为了测试Swift 2.1中的Singleton:

class FGSingleton {
    static let sharedInstance = FGSingleton()

    var gameScore: Int = 0

    let path = NSBundle.mainBundle().pathForResource("Data", ofType: "plist")
    //below line is creating issue because of using sharedInstance
    let dict = NSDictionary(contentsOfFile: sharedInstance.path!)

    // METHODS
    private init() {
        print(__FUNCTION__)
    }
    func displayGameScore() {
        print("\(__FUNCTION__) \(self.gameScore)")
    }
    func incrementGameScore(scoreInc: Int) {
        self.gameScore += scoreInc
    }
}
但是当我像这样调用func
FGSingleton.sharedInstance.displayGameScore()
时,它既不会调用该函数,也不会从
init
打印。我试着调试它,发现游标从未进入函数内部


这是由于我在上面评论的错误行造成的。你知道如何从sharedInstance调用一个全局变量来给另一个全局变量赋值吗?

我找到的最简单的解决方案是将全局变量初始化为可选变量,然后从
init()中的另一个全局变量给它赋值。这是我的更新代码:

class FGSingleton {
    static let sharedInstance = FGSingleton()

    var gameScore: Int = 0

    let path = NSBundle.mainBundle().pathForResource("Data", ofType: "plist")
    //initialize as optional
    let dict: NSDictionary?

    // METHODS
    private init() {
        print(__FUNCTION__)
        dict = NSDictionary(contentsOfFile: self.path!)
    }
    func displayGameScore() {
        print("\(__FUNCTION__) \(self.gameScore)")
    }
    func incrementGameScore(scoreInc: Int) {
        self.gameScore += scoreInc
    }
}

如果有其他更好的解决方案,请告诉我。

首先,您的代码不是Swift 2.1(
println
)。另外,当我试图用你的代码调用
FGSingleton.sharedInstance.displayGameScore()
时,一切正常。对不起,我的打字错误。。。但是这个示例代码在ViewController的
ViewDidLoad()
函数中不起作用。我也试过了。它在ViewController的
viewDidLoad()
中对我有效