How to define static constant in a class in swift

前端 未结 7 874
日久生厌
日久生厌 2020-12-23 19:59

I have these definition in my function which work

class MyClass {
    func myFunc() {
        let testStr = \"test\"
        let testStrLen = countElements(t         


        
相关标签:
7条回答
  • 2020-12-23 20:52

    If you actually want a static property of your class, that isn't currently supported in Swift. The current advice is to get around that by using global constants:

    let testStr = "test"
    let testStrLen = countElements(testStr)
    
    class MyClass {
        func myFunc() {
        }
    }
    

    If you want these to be instance properties instead, you can use a lazy stored property for the length -- it will only get evaluated the first time it is accessed, so you won't be computing it over and over.

    class MyClass {
        let testStr: String = "test"
        lazy var testStrLen: Int = countElements(self.testStr)
    
        func myFunc() {
        }
    }
    
    0 讨论(0)
提交回复
热议问题