i'm new to swift, i have a project in Xcode 7 Beta, and i have extension files and etc. i have 3 .swift files (not for view controllers) in my project, and i want to define a variable or constant in one of them and access that , all over the project. for example define a var in First.swift , and access to that in Second or Third.swift files. i know about NSUserDefaults in Xcode, but i don't want to use that. Also i know that how i can pass data between viewcontrollers (using prepareforsegue and etc.) but i want to pass data between .swift files.
-
You can create object in Appdelegate. – iOS Dev Jul 03 '15 at 09:12
-
how? i tried to define a variable in the AppDelegate.swift's class. but it doesn't working. – MohammedMaher Aloha Jul 03 '15 at 09:20
-
can you paste here your variable? – iOS Dev Jul 03 '15 at 09:23
-
var ammenane:String = "" //this is my variable in appdelegate – MohammedMaher Aloha Jul 03 '15 at 09:36
-
i hope you have written this before didFinishLaunchingWithOptions – iOS Dev Jul 03 '15 at 09:38
-
sure, i inserted this after the main class's { and before finish launching with options. – MohammedMaher Aloha Jul 03 '15 at 09:45
-
Okay, add "var ammenane : String!" before "didFinishLaunchingWithOptions" and initialize in didFinishLaunchingWithOptions or where ever you want. – iOS Dev Jul 03 '15 at 09:51
3 Answers
One way to do it is you can encapsulate them in struct
and can access anywhere.
You can define static variables or constant in swift also.Encapsulate in struct
struct MyVariables {
static var yourVariable = "someString"
}
You can use this variable in any class or anywhere:
let string = MyVariables.yourVariable
println("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"
Or you can declare global variables which you can access anywhere.
Reference from HERE.

- 1
- 1

- 71,228
- 33
- 160
- 165
-
thanks for your answer, where i should write this code? i wrote this in the class of my viewcontroller.swift file, but i can't access. – MohammedMaher Aloha Jul 03 '15 at 09:34
-
Take a look at http://www.raywenderlich.com/86477/introducing-ios-design-patterns-in-swift-part-1
The idea is to create one instance of a class and access it anywhere in your files/classes.
If you just need to share constants, the Dharmesh's solution is simpler.

- 4,870
- 1
- 23
- 30
You can create custom subclass of NSObject class. Declare all variables there. Create single instance of object of that class and access variables through the object of that class in any view controller.
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: Singleton? = nil
static var yourVariable = "someString"
}
dispatch_once(&Static.onceToken) {
Static.instance = Singleton()
}
return Static.instance!
}
}
then in any viewController, you can access the variables.

- 12,613
- 2
- 41
- 54

- 1,200
- 2
- 9
- 19