Skip to content

Instantly share code, notes, and snippets.

@rothomp3
Created October 5, 2015 21:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rothomp3/56c646b2c3488255bc75 to your computer and use it in GitHub Desktop.
Save rothomp3/56c646b2c3488255bc75 to your computer and use it in GitHub Desktop.
Example of building an inheritance-friendly singleton class in Swift
#!/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)")
@nareshpareek
Copy link

Can you help in translating to Swift 3.
Thanks in advance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment