Created
October 5, 2015 21:40
-
-
Save rothomp3/56c646b2c3488255bc75 to your computer and use it in GitHub Desktop.
Example of building an inheritance-friendly singleton class in Swift
This file contains hidden or 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
#!/usr/bin/xcrun -sdk macosx swift | |
import Foundation | |
public protocol SharedInstanceType | |
{ | |
init() | |
} | |
private struct TokenKey | |
{ | |
static let tokenKey = "tokenKey" | |
} | |
private struct InstanceKey | |
{ | |
static let instanceKey = UnsafePointer<Void>() | |
} | |
private extension SharedInstanceType where Self: AnyObject | |
{ | |
static var tokenData: NSMutableData { | |
get { | |
var result = objc_getAssociatedObject(self, TokenKey.tokenKey) | |
if result == nil { | |
result = NSMutableData(length: sizeof(dispatch_once_t)) | |
objc_setAssociatedObject(self, TokenKey.tokenKey, result, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
return result as! NSMutableData | |
} | |
} | |
static var _instance: Self? { | |
get { | |
if let instance = objc_getAssociatedObject(self, InstanceKey.instanceKey), | |
let result = instance as? Self | |
{ | |
return result | |
} | |
else { | |
return nil | |
} | |
} | |
set { | |
if let value = newValue | |
{ | |
objc_setAssociatedObject(self, InstanceKey.instanceKey, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
} | |
} | |
} | |
public extension SharedInstanceType where Self: AnyObject | |
{ | |
static var sharedInstance:Self { | |
get { | |
dispatch_once(UnsafeMutablePointer<dispatch_once_t>(self.tokenData.mutableBytes)) { | |
self._instance = Self() | |
} | |
return _instance ?? Self() | |
} | |
} | |
} | |
class FooBar: SharedInstanceType | |
{ | |
required init() {} | |
} | |
class Foo: FooBar | |
{ | |
} | |
class Baz: Foo | |
{ | |
} | |
print("\(FooBar.sharedInstance.dynamicType)") | |
print("\(Foo.sharedInstance.dynamicType)") | |
print("\(Baz.sharedInstance.dynamicType)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you help in translating to Swift 3.
Thanks in advance