n179911 n179911 - 7 months ago 16
Swift Question

How to define static constant in a class in swift

I have these definition in my function which work

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


But if I move 'testStr' and 'testStrLen' to the class level, it won't compile. It said 'MyClass.Type does not have a member named 'testStr'.

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

func myFunc() {

}
}


How can I fix this? I don't want to pay the penalty for counting len of a constant 'test' everytime.

Based on my understanding of the comments below, I need to do this:

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

func myFunc() {

}
}


Is there a way I don't need to type/enter "test" twice?
Thanks.

Answer

If you put the code in an initializer it will compile. You will have to instantiate your class when you want to use those properties, though.

class MyClass {
    let testStr: String
    let testStrLength: Int

    init() {
        self.testStr = "Test"
        self.testStrLength = countElements(testStr)
    }

    func myFunc() {

    }
}

let myClass = MyClass()
myClass.testStrLength
Comments