I recently watched a video tutorial in Lynda.com and I noticed that the author declared a few global variables which included two class instances. The main reason for my question is because I have heard that we need to try to avoid using global variables unless your really need them. I can see using global variables for NSUserDefaults' Keys
but I'm not sure about global instances.
Here is the code showing the global variables declarations. I'm only concerned about variables masterView
and detailViewController
.
import UIKit
var objects:[String] = [String]()
var currentIndex:Int = 0
var masterView:MasterViewController?
var detailViewController:DetailViewController?
let kNotes:String = "notes"
let BLANK_NOTE:String = "(New Note)"
class MasterViewController: UITableViewController {
// class code
}
Is it ok to declare your class instances as global variables?
It is certainly OK to use global variables in your Swift code from the technical point of view, in the sense that your program is not going to crash or otherwise "misbehave" because of that. When you are building a quick example for a demonstration, global variables provide a convenient way to shorten the code.
However, there are drawbacks to using mutable global variables that makes their use questionable. Specifically, they break encapsulation. Looking at the code that you provided, two variables
var objects:[String] = [String]()
var currentIndex:Int = 0
should be hidden in a model object, over which you have some degree of control.
Using globals may produce some unexpected behavior if you are not careful about clearing them. For example
var masterView:MasterViewController?
var detailViewController:DetailViewController?
may retain references to view controllers that are no longer visible.
That's okay to declare a class instances as a global variable, if you want to prefer use of only one instance of that class through out your app work.
NOTE: you can hide those properties & functions of that instance by making those Private, which you don't want to be accessed by global instance variable.
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