-2

I'm creating an iOS 8 app and I want to create a string variable that is accessible to all class. I tried to create global.swift with a string variable in it. I can access the variable but, everytime I initialize the class again using this line let globalVar = global() the value that I've passed returns a nil value. Can someone help me with this. Thank you.

user3300758
  • 275
  • 1
  • 4
  • 13

3 Answers3

1

You can put the variable in your AppDelegate, which is a singleton. See this post for how to access the AppDelegate

How do I get a reference to the app delegate in Swift?

Community
  • 1
  • 1
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
1

Put

public static var global = "String"

in any class. Access via Classname.global.

Howard Lovatt
  • 968
  • 1
  • 8
  • 15
0

Just use your Global.swift file and put your global variables and functions inside without any class around it.

//
//  Global.swift
// 

let myConstant = 5

func myGlobalFunction() {
    // ...
}

You can access those variables and functions all around your module.

heyfrank
  • 5,291
  • 3
  • 32
  • 46