Singleton and init with parameter

前端 未结 6 1359
孤街浪徒
孤街浪徒 2020-12-24 07:02

I want to use the singleton pattern in my class which has a private init with parameter. It also has a class function called setup which configures

6条回答
  •  误落风尘
    2020-12-24 07:30

    This seems to be the simplest way to implement the singleton in swift:

    private let _AsteroidSharedInstance: Asteroid?
    
    class Asteroid {
        var config: ASTConfig?
    
        class func setup(config: config) {
            _AsteroidSharedInstance = Asteroid(config: config)
        }
    
        class var sharedInstance: Asteroid {
            if _AsteroidSharedInstance == nil {
                println("error: shared called before setup")
            }
    
            return _AsteroidSharedInstance
        }
    
        init(config: config) {
            self.config = config
        }
    }
    

    with the usage:

    Asteroid.sharedInstance()
    

    Source and Source

提交回复
热议问题