How to define static constant in a class in swift

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

    Tried on Playground

    
    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 static func singletonFunction() { //accessable print("Print singletonFunction testInt=\(testInt)") var newInt = testStrLen newInt = newInt + 1 print("Print singletonFunction testStr=\(testStr)") } } func ownFunction() { //not accessable //var newInt1 = Constants.testInt + 1 var newInt2 = Constants.testStrLen newInt2 = newInt2 + 1 print("Print ownFunction testStr=\(Constants.testStr)") print("Print ownFunction newInt2=\(newInt2)") } } let newInt = MyClass.Constants.testStrLen print("Print testStr=\(MyClass.Constants.testStr)") print("Print testInt=\(newInt)") let myClass = MyClass() myClass.ownFunction() MyClass.Constants.singletonFunction()

提交回复
热议问题