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 researched for a way to do it, but have not found an answer. I have tried making giving the array a public scope, but I get a complier warning which says Declaring public variable from internal class
and when I try to access it in a different file, I get an error that says Use of unresolved identifier 'arrayObjectives'
How would I go about making that array globally accessible to all files in the application and where would I instantiate that array?
Here you can see section is a global variable we have defined, inside a class but outside a function. We can use an access modifier prefixed with the global variable as per the need. You can also define a global variables as static by prefixing static keyword.
From the official Swift programming guide: Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily. You can define it in any file and can access it in current module anywhere.
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With