What is the use of “static” keyword if “let” keyword used to define constants/immutables in swift?

后端 未结 6 496
无人共我
无人共我 2020-12-07 09:40

I\'m little bit confused about using static keyword in swift. As we know swift introduces let keyword to declare immutable objects. Like de

6条回答
  •  猫巷女王i
    2020-12-07 10:13

    I will break them down for you:

    • var : used to create a variable
    • let : used to create a constant
    • static : used to create type properties with either let or var. These are shared between all objects of a class.

    Now you can combine to get the desired out come:

    • static let key = "API_KEY" : type property that is constant
    • static var cnt = 0 : type property that is a variable
    • let id = 0 : constant (can be assigned only once, but can be assigned at run time)
    • var price = 0 : variable

    So to sum everything up var and let define mutability while static and lack of define scope. You might use static var to keep track of how many instances you have created, while you might want to use just varfor a price that is different from object to object. Hope this clears things up a bit.

    Example Code:

    class MyClass{
        static let typeProperty = "API_KEY"
        static var instancesOfMyClass = 0
        var price = 9.99
        let id = 5
    
    }
    
    let obj = MyClass()
    obj.price // 9.99
    obj.id // 5
    
    MyClass.typeProperty // "API_KEY"
    MyClass.instancesOfMyClass // 0
    

提交回复
热议问题