Declaring Global Variables in Swift

后端 未结 4 613
我寻月下人不归
我寻月下人不归 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]
    
    0 讨论(0)
  • 2020-12-09 16:20

    This is how I did it...

    class MessageViewCell {
        struct MessageViewCellHeightCache {
            static var cache: [String:CGFloat] = Dictionary<String, CGFloat>()
        }
    }
    

    And I accessed it as follows:

    MessageViewCell.MessageViewCellHeightCache.cache["first"] = 12.0
    
    0 讨论(0)
  • 2020-12-09 16:23

    From the Swift Programming Language -

    Global variables are variables that are defined outside of any function, method, closure, or type context

    So you can simply declare your variable at the top of any file straight after the import statements.

    However, I would suggest you seriously reconsider. Generally globals aren't a good idea. You are better off with properties on a singleton or using dependency injection.

    Your second question "where would I instantiate the array?" is part of the reason why globals are bad - their lifecycle isn't well defined in terms of your other objects. A singleton that is initialised on first use eliminates this issue.

    0 讨论(0)
  • 2020-12-09 16:28

    You can set global Array like this way :

    import UIKit
    
    var abc : String = String()
    

    and you can access it in any other file like :

    abc = "ABC"
    
    0 讨论(0)
提交回复
热议问题