3

Looking at:

Using a dispatch_once singleton model in Swift

I see a very generic pattern for creating a shared singleton instance of my class. What I'd like to be able to do is create an extension for "all classes" that implements this sharedInstance method with generics.

I don't see any syntax for doing this; anybody want to take a crack at it?

Community
  • 1
  • 1
Gavin
  • 6,495
  • 3
  • 21
  • 22

3 Answers3

2

As others have pointed out, Swift offers a simpler way to create singletons.

As an example: let's say we have a class called Model, and we want to have a single instance, visible throughout our app. All we need to write in the global scope is:

let modelSingleton = Model()

This will create an instance of the Model class, visible everywhere, and that cannot be replaced by another instance (Hmmm, that's pretty much what one would expect from a singleton, isn't it?).

Now, this way of doing would, on the other hand, still allow you to create other Model instances, apart from the singleton. While this departs from the official definition of singletons in other languages, this approach would have the interesting advantage of allowing the creation of other instances for testing purposes (singletons have bad press in the unit testing world :) ).

Swift will soon offer everything needed to create real Singleton<T> classes (it's hard now because class vars aren't allowed yet). But that being said, the approach described above will probably be more than enough for many Swift programmers.

Jean Le Moignan
  • 22,158
  • 3
  • 31
  • 37
0

I don't think this is possible.

Even if it was possible to extend Any / AnyObject, every object would share the same implementation of the sharedInstance singleton getter, and therefore the same static instance variable. Thus, instance would get set to an instance of the first class on which sharedInstance was called.

extension Any {
    class var sharedInstance:TPScopeManager {
        get {
            struct Static {
                static var instance : TPScopeManager? = nil
            }

            if !Static.instance {
                Static.instance = TPScopeManager()
            }

            return Static.instance!
        }
    }
}

...

NSString.sharedInstance() // Returns an NSString
NSArray.sharedInstance() // Returns the same NSString object!
Austin
  • 5,625
  • 1
  • 29
  • 43
0

In Swift you can make an extension to NSObject, but you can't extend Any/AnyObject

atermenji
  • 1,338
  • 8
  • 19