When to use static constant and variable in Swift?

后端 未结 4 1688
刺人心
刺人心 2020-12-07 13:16

There are some posts for how to write code for static constant and static variable in Swift. But it is not clear when to use static constant<

4条回答
  •  不知归路
    2020-12-07 14:12

    When you define a static var/let into a class (or struct), that information will be shared among all the instances (or values).

    Sharing information

    class Animal {
        static var nums = 0
    
        init() {
            Animal.nums += 1
        }
    }
    
    let dog = Animal()
    Animal.nums // 1
    let cat = Animal()
    Animal.nums // 2
    

    As you can see here, I created 2 separate instances of Animal but both do share the same static variable nums.

    Singleton

    Often a static constant is used to adopt the Singleton pattern. In this case we want no more than 1 instance of a class to be allocated. To do that we save the reference to the shared instance inside a constant and we do hide the initializer.

    class Singleton {
        static let sharedInstance = Singleton()
    
        private init() { }
    
        func doSomething() { }
    }
    

    Now when we need the Singleton instance we write

    Singleton.sharedInstance.doSomething()
    Singleton.sharedInstance.doSomething()
    Singleton.sharedInstance.doSomething()
    

    This approach does allow us to use always the same instance, even in different points of the app.

提交回复
热议问题