IOS8 + Swift: create a true singleton class

I create a single class in Swift as follows:

class SingletonClass {

    class var sharedInstance: SingletonClass {
        struct Singleton {
            static let instance = SingletonClass()
        }

        return Singleton.instance
    }


    var a: Int?
    var b: Int?
    var c: Int?
}

This allows me to access the shared instance from anywhere:

SingletonClass.sharedInstance

While this works, it does not make this instance the only one possible in the whole system, and this is what singles are talking about.
This means that I can still create a completely new instance, for example:

let DifferentInstance: SingletonClass = SingletonClass()

And the shared instance is no longer the only one.



So my question is this: is there a way in Swift to create a real singleton class where only one instance is possible in a system-wide one?

+4
source share
3 answers

:

private init() {}

.

+14

. singleton - , . UIApplication sharedApplication, , sharedApplication. NSNotificationCenter defaultCenter, , defaultCenter. , , factory, , . , .

+2

, , dispatch_once. .

( structs enums) , , dispatch_once, , . dispatch_once : .

private let _singletonInstance = SingletonClass()
class SingletonClass {
  class var sharedInstance: SingletonClass {
    return _singletonInstance
  }
}

More info here. https://github.com/hpique/SwiftSingleton

0
source

All Articles