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

后端 未结 6 489
无人共我
无人共我 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条回答
  •  [愿得一人]
    2020-12-07 10:20

    Static Variables are belong to a type rather than to instance of class. You can access the static variable by using the full name of the type.

    Code:

    class IOS {
    
      var iosStoredTypeProperty = "iOS Developer"
    
      static var swiftStoredTypeProperty = "Swift Developer"
    
     }
    
     //Access the iosStoredTypeProperty by way of creating instance of IOS Class
    
    let iOSObj = IOS()
    
    print(iOSObj.iosStoredTypeProperty)  // iOS Developer
    
    
     //print(iOSObj.swiftStoredTypeProperty) 
     //Xcode shows the error 
     //"static member 'swiftStoredTypeProperty' cannot be used on instance of type IOS”
    
    
     //You can access the static property by using full name of the type
    print(IOS.swiftStoredTypeProperty)  // Swift Developer
    

    Hope this helps you..

提交回复
热议问题