Passing Data Between .Swift Files in Xcode [closed

2019-09-18 06:06发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

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.



标签: ios xcode swift