Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a constants file on Swift?

Tags:

ios

swift

swift3

I have around 10 Swift 3 applications.

They are almost similar but there are some fields that changes in each application and I would like that these values could be used in the entirely program (for example: the name of each company, the primary colour on the application, etc). These values will be constant in the whole program.

I would like to create one constants file by application so the values that will be used on each application will be different from the others so I will not have to repeat on each program each value all the time. For example, if I set a constant named company and change its value to company1, company2, etc... depending on the file I can use that company constant in all the applications. So I will not have to replace the variable manually in the whole application each time I create a new one. Just replacing the corresponding values to each application.

So, is it possible to create a constants file? Maybe adding a special class. I guess that maybe it has another specific name but I could not find it.

Thanks in advance!

like image 537
Francisco Romero Avatar asked Nov 28 '16 13:11

Francisco Romero


2 Answers

Yes you can create Constants file in Swift. Below are the ways.:

struct Constants {
    //App Constants
    static let APP_NAME = "YOUR_APP_NAME"
}

Usage:

print(Constants.APP_NAME)

Create a class and access via creating object:

class Constants{
     let APP_NAME = "YOUR APP NAME"
}

Usage:

let constInstance = Constants()
print(constInstance.APP_NAME)

The most efficient way is to go with struct.

like image 57
Sohil R. Memon Avatar answered Oct 06 '22 01:10

Sohil R. Memon


It actually depends on what you want to define:

  • In case of app's fonts, for example, declare an UIFont extension. In this way the precompiler can help you while writing code.

  • In case of any particular constant (string, integers, etc..), I would create a Constants.swift file which contains only enums. The enum in this case is better than class or struct because it cannot be wrongly initialized

    enum Constants { static let appIdentifier: String = "string" }

It can only be used in this way: Constants.appIdentifier It cannot be initialized by doing Constants() (compiler will throw an error).

See https://www.natashatherobot.com/swift-enum-no-cases/ for more info

like image 26
Luca D'Alberti Avatar answered Oct 06 '22 00:10

Luca D'Alberti