Having hard time implement a simple singleton in swift

前端 未结 1 1827
深忆病人
深忆病人 2020-11-29 12:53

I have created a new file ->swift file . called Globals.Swift Then in there I have done :

class Globals {

    static let shared         


        
相关标签:
1条回答
  • You can't just have var = xxx in an init. The variable has to be declared at the class top level.

    Example of using your singleton:

    class Globals {
    
        static let sharedInstance = Globals()
    
        var max: Int
    
        private init() {
            self.max = 100
        }
    
    }
    
    let singleton = Globals.sharedInstance
    
    print(singleton.max) // 100
    
    singleton.max = 42
    
    print(singleton.max) // 42
    

    When you need to use the singleton in another class, you just do this in the other class:

    let otherReferenceToTheSameSingleton = Globals.sharedInstance
    

    Update following Martin R and Caleb's comments: I've made the initializer private. It prevents, in other Swift files, the initialization of Globals(), enforcing this class to behave as a singleton by only being able to use Globals.sharedInstance.

    0 讨论(0)
提交回复
热议问题