Trying to get a Singleton class going in Swift. I'm not getting any errors, but its also just plain not working properly.
Here's the code:
// The Singleton class:
class DataWarehouse {
class var sharedData:DataWarehouse {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : DataWarehouse? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = DataWarehouse()
}
return Static.instance!
}
// Here's a variable that I want to pass around to other classes:
var x = 10
}
Next, I created two classes that can access the value of x
and use it, change its value, etc:
class ClassA {
var theData = DataWarehouse()
func changeX() {
// First, log out the current value of X:
println("ClassA ==> x is currently: \(theData.x)")
// Next, change it:
theData.x = -50
println("ClassA ==> x was just set to: \(theData.x)")
}
}
Here's the second class - its basically the same as ClassA:
class ClassB {
var theData = DataWarehouse()
func changeX() {
// First, log out the current value of X:
println("ClassB ==> x is currently: \(theData.x)")
// Next, change it:
theData.x = -88
println("ClassB ==> x was just set to: \(theData.x)")
}
}
Finally, in main.swift
I put the whole thing together:
let objectA = ClassA()
objectA.changeX()
let objectB = ClassB()
objectB.changeX()
The output I get is:
ClassA ==> x is currently: 10
ClassA ==> just set x to: -50
ClassB ==> x is currently: 10
ClassB ==> just set x to: -88
So the value of x
doesn't truly get updated, its always 10.
What am I doing wrong?