Access variable in different class – Swift

I have solved this by creating a generic main class which is accessible to all views. Create an empty swift file, name it ‘global.swift’ and include it in your project:

global.swift:

class Main {
  var name:String
  init(name:String) {
    self.name = name
  }
}
var mainInstance = Main(name:"My Global Class")

You can now access this mainInstance from all your view controllers and the name will always be “My Global Class”. Example from a viewController:

viewController:

override func viewDidLoad() {
        super.viewDidLoad()
        println("global class is " + mainInstance.name)
    }

Leave a Comment