fs_tigre fs_tigre - 4 years ago 170
Swift Question

Is it common/ok to declare global class instances in Swift/iOS

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download