Error404 Error404 - 7 days ago 6
iOS Question

Is it possible to create a constants file on Swift?

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!

Answer

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.

Comments