I have a few classes i.e. User, Settings... that I use in most of my ViewControllers. Because I use them often, is it better if I have only one instance of them to use globally, or a new instance for each class?

In AppDelegate:

let user = User()

class AppDelegate: UIResponder, UIApplicationDelegate {


In each class:

class TimerViewController: UIViewController {

    private let user = User()

2 Answers

Sh_Khan On Best Solutions

For the current state being globally is better

let user = User()

but it's much better to make it a singleton

class Service {
  static let shared = Service()
  let user = User()

so not to confuse other developers when read the code won't know whether this global var is local/instance/global , so being singleton will sort this

Anand On

My two cents

It is always better to declare it where you actually need instead of declaring it globally. It is good practice to limit the scope the variables that we use so that it gets deallocated and cleared from memory when its job is over. Here, it is clear that there is only one owner for that instance.

Declaring global objects will lead to maintaining global state for the instance properties and since it is open to all classes, it will not be clear which class is changing what.Here, everyone is like owner of this instance.So, It is always better to avoid it.