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
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]
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
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.
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"