Access static variables within class in Swift

后端 未结 7 2115
独厮守ぢ
独厮守ぢ 2020-12-08 09:24

Is ClassName.staticVaribale the only way to access static variable within the class? I want something like self, but for class. Like class.st

相关标签:
7条回答
  • 2020-12-08 09:51

    It looks like in Swift 4.2 the inner class and instance variable can directly access the static variable without the prefix of the class name. However, you still need the class name within a function.

    class MyClass {
        static let staticProperty = 0
        let property = staticProperty //YES
    
        class Inner {
            func method() {
                print(staticProperty) //YES
            }
        }
    
        func method() {
            print(staticProperty) //NO
            print(MyClass.staticProperty) //YES
        }
    }
    
    0 讨论(0)
提交回复
热议问题