Skip to content

Instantly share code, notes, and snippets.

@rothomp3
Created October 5, 2015 21:40
Show Gist options
  • Select an option

  • Save rothomp3/56c646b2c3488255bc75 to your computer and use it in GitHub Desktop.

Select an option

Save rothomp3/56c646b2c3488255bc75 to your computer and use it in GitHub Desktop.

Revisions

  1. Robert Thompson created this gist Oct 5, 2015.
    84 changes: 84 additions & 0 deletions singleton.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    #!/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)")