I'm learning Swift and iOS app development and I was wondering in which cases (if there are some) I should use global variables and constants in an iOS app.
Global variables are variables that are defined outside of any function, method, closure, or type context. Local variables are variables that are defined within a function, method, or closure context.
Using global variables usually seems inelegant and not advisable (it is in fact not recommended by most guides and tutorials) and to pass data between view controller I use the prepareForSegue(_: sender:)
method.
There are some cases however where it seems to me that the use of globals would make the code simpler and faster.
For example Apple recommends to store a NSDateFormatter
or a NSNumberFormatter
for each format pattern and not to recreate or to change one every time it is needed. In an app I'm developing to learn the language, most of the view controllers use a NSDateFormatter
and a NSNumberFormatter
and creating a new one for each view controller might not be a good idea. I could pass it with prepareForSegue, but I thought that maybe in this case it would be better to use a global var holding an instance of the formatter that every view controller could use.
So are there any cases where I should use global variables?