How to define static constant in a class in swift

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

    Some might want certain class constants public while others private.

    private keyword can be used to limit the scope of constants within the same swift file.

    class MyClass {
    
    struct Constants {
    
        static let testStr = "test"
        static let testStrLen = testStr.characters.count
    
        //testInt will not be accessable by other classes in different swift files
        private static let testInt = 1
    }
    
    func ownFunction()
    {
    
        var newInt = Constants.testInt + 1
    
        print("Print testStr=\(Constants.testStr)")
    }
    
    }
    

    Other classes will be able to access your class constants like below

    class MyClass2
    {
    
    func accessOtherConstants()
    {
        print("MyClass's testStr=\(MyClass.Constants.testStr)")
    }
    
    } 
    

提交回复
热议问题