Declaring Global Variables in Swift

后端 未结 4 607
我寻月下人不归
我寻月下人不归 2020-12-09 16:06

I want to make a global array of custom objects that can be accessed throughout the app (AppDelegate, ViewController classes, TableViewController classes, etc). I have resea

4条回答
  •  眼角桃花
    2020-12-09 16:15

    Try making a new Swift file with this:

    struct Constants {
    
      static let appName: String = "My App"
    
      struct Colors {
    
        static let colorTextStandard = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.3) //#000000
    
      }
    
      struct Data {
    
        static var myStrings = [String]()  // Yea, this is not a constant, but that's alright...
    
      }
    
    }
    

    You can then refer to those global constants (or you can make them variables) using:

    Constants.appName
    

    or

    Constants.Colors.colorTextStandard
    

    or

    Constants.Data.myStrings = [stringOne, stringTwo]
    

提交回复
热议问题