Last active
August 29, 2015 14:02
-
-
Save plumhead/f5947ab7cf42107bb87e to your computer and use it in GitHub Desktop.
Swift Singletons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground - noun: a place where people can play | |
import UIKit | |
import Foundation | |
import Swift | |
class MySingleton { | |
var amount : Float! | |
init(_ a : Float){amount = a} | |
// VERSION - 1 | |
// We can't define static class level vars but structs can | |
struct InstanceSingleton { | |
static var done : dispatch_once_t = 0 | |
static var instance : MySingleton? | |
} | |
// A more traditional approach using the dispatch_once model | |
class func Instance() -> MySingleton { | |
dispatch_once(&InstanceSingleton.done, { | |
InstanceSingleton.instance = MySingleton(123.45) | |
}) | |
return InstanceSingleton.instance! | |
} | |
/* | |
This works but exposes a struct to the outside world which can be used to access the statics | |
*/ | |
// VERSION - 2 | |
// can we just create a 'lazy' initialised instance without requiring dispatch_once | |
// I'm not sure on thread safety - will need to check the docs to see if defined! | |
struct InstanceSingleton2 { | |
static var instance : MySingleton = MySingleton(222.33) | |
} | |
class func Instance2() -> MySingleton {return InstanceSingleton2.instance} | |
// VERSION - 3 | |
class func Instance3() -> MySingleton { | |
// we actually seem to get a private static here | |
struct InstanceSingleton3 { | |
static let instance : MySingleton = MySingleton(444.55) | |
} | |
return InstanceSingleton3.instance | |
} | |
} | |
let a = MySingleton(10.0) | |
let b = MySingleton(20.0) | |
let c = MySingleton.Instance() | |
let d = MySingleton.Instance() | |
a === a // true | |
b === b // true | |
a === b // false | |
a === c // false | |
a === d // false | |
c === d // true | |
let e = MySingleton.Instance2() | |
let f = MySingleton.Instance2() | |
e === f // true | |
c === e // false | |
let g = MySingleton.Instance3() | |
// VERSION - 1 lets us do this | |
MySingleton.InstanceSingleton.done = 0 | |
let c1 = MySingleton.Instance() | |
c === c1 // false - we've reset the static so get a new instance | |
c.amount /// 123.45 | |
c1.amount /// 123.45 (same value but different object) | |
// VERSION - 2 | |
MySingleton.InstanceSingleton2.instance = MySingleton(888.99) | |
let e1 = MySingleton.Instance2() | |
e === e1 // false - we've overwritten the original instance | |
e.amount /// 222.33 | |
e1.amount /// 888.99 | |
// VERSION - 3 | |
// We have no visibility of the underlying static nested as it is behind the function | |
MySingleton.Instance3().amount // returns 444.55 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment