Access static variables within class in Swift

后端 未结 7 2161
独厮守ぢ
独厮守ぢ 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:26

    There is a way in Swift to make Marcel's answer satisfy even most picky style-guide gods

    class MyClass {
    
        private typealias `Self` = MyClass
    
        static let MyConst = 5
    
        func printConst() {
            print(Self.MyConst)
        }
    }
    

    That makes Self available like in protocols when you want access associated type declaration. I am not sure about Swift 1 because never tried it but in Swift 2 it works perfectly

提交回复
热议问题