Skip to content

Instantly share code, notes, and snippets.

@bsneed
Forked from rothomp3/singleton.swift
Created October 5, 2015 21:40
Show Gist options
  • Save bsneed/ce19ad6ec9c5585bfdbf to your computer and use it in GitHub Desktop.
Save bsneed/ce19ad6ec9c5585bfdbf 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

Hello, Could you help in translating it to Swift 3
Thanks in advance

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