Global constant Swift 2

0

Hello, I would like to know how to create a global settings file.

I'm using a Lib to do http query, Alamofire.

I'd like it anywhere that in any file I called the constant it would be accessed. Example:

Alamofire.request(.GET, FILECONFIG.CONSTANTEURLGLOBAL, parameters: ["foo": "bar"])
     .responseJSON { response in
         print(response.request)  // original URL request
         print(response.response) // URL response
         print(response.data)     // server data
         print(response.result)   // result of response serialization

         if let JSON = response.result.value {
             print("JSON: \(JSON)")
         }
     }

In the part of the code that has the expression FILECONFIG.CONSTANTEURLGLOBAL would be the one that would contain the URL address that I want to access.

Soon the configuration file would look something like this:

let CONSTANTEURLGLOBAL1 = "http://...."
let CONSTANTEURLGLOBAL2 = "http://...."
let CONSTANTEURLGLOBAL3 = "http://...."

I'm extremely new to swift so thank you in advance.

    
asked by anonymous 15.04.2016 / 23:11

2 answers

1

You can use defined structures in a file named Constants.swift , so you can store and access the constants of the entire app cleanly:

struct Config {
    static let baseURL: NSURL(string: "http://www.example.org/")!
    static let splineReticulatorName = "foobar"
}

struct Color {
    static let primaryColor = UIColor(red: 0.22, green: 0.58, blue: 0.29, alpha: 1.0)
    static let secondaryColor = UIColor.lightGrayColor()
}


// Uso:

Alamofire.request(.GET, Config.baseURL, parameters: ["foo": "bar"])
     .responseJSON { response in
         print(response.request)  // original URL request
         print(response.response) // URL response
         print(response.data)     // server data
         print(response.result)   // result of response serialization
     if let JSON = response.result.value {
         print("JSON: \(JSON)")
     }
 }

You can find more in the document I translated: Swift Style Guide - Constants

    
18.04.2016 / 16:41
0

You can create a Swift class with the settings you want and put your variables there. then in any class you instantiate the class of configurations and access the constant that you want.

Example:

Create a Config.swift class

put the constant let CONSTANTEURLGLOBAL1="http: // ...."

Then in the other class you want, you create: var constant = Config () then just call: constant.CONSTANTEURLGLOBAL1

    
16.04.2016 / 18:59