Global constant Swift 2

Asked

Viewed 159 times

0

Ola would like to know how to create a global settings file.

I’m wearing a Lib for http, Alamofire query.

I’d like anywhere in any file I called the constant to 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 account that would contain the URL address I want to access.

Soon the configuration file would be something like this:

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

I am extremely new to Swift so thanks in advance.

2 answers

1


You can use structures defined in a file called Constants.swift, can thus 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

0

You can create a Swift class with the settings you want and put your variables there. then in any class you instate the configuration class and access the constant you want.

Example:

Create a Config.Swift class

puts the Let constant CONSTANTEURLGLOBAL1 = "http://...."

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.