Access static variables within class in Swift

There are two ways to access a static property/method from a non-static property/method:

  1. As stated in your question, you can prefix the property/method name with that of the type:

    class MyClass {
        static let staticProperty = 0
    
        func method() {
            print(MyClass.staticProperty)
        }
    }
    
  2. Swift 2: You can use dynamicType:

    class MyClass {
        static let staticProperty = 0
    
        func method() {
            print(self.dynamicType.staticProperty)
        }
    }
    

    Swift 3: You can use type(of:) (thanks @Sea Coast of Tibet):

    class MyClass {
        static let staticProperty = 0
    
        func method() {
            print(type(of: self).staticProperty)
        }
    }
    

If you’re inside a static property/method you do not need to prefix the static property/method with anything:

class MyClass {
    static let staticProperty = 0

    static func staticMethod() {
        print(staticProperty)
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)