How to define static constant in a class in swift

前端 未结 7 901
日久生厌
日久生厌 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:32

    If I understand your question correctly, you are asking how you can create class level constants (static - in C++ parlance) such that you don't a) replicate the overhead in every instance, and b have to recompute what is otherwise constant.

    The language has evolved - as every reader knows, but as I test this in Xcode 6.3.1, the solution is:

    import Swift
    
    class MyClass {
        static let testStr = "test"
        static let testStrLen = count(testStr)
    
        init() {
            println("There are \(MyClass.testStrLen) characters in \(MyClass.testStr)")
        }
    }
    
    let a = MyClass()
    
    // -> There are 4 characters in test
    

    I don't know if the static is strictly necessary as the compiler surely only adds only one entry per const variable into the static section of the binary, but it does affect syntax and access. By using static, you can refer to it even when you don't have an instance: MyClass.testStrLen.

提交回复
热议问题