MarkosDarkin MarkosDarkin - 3 months ago 16
iOS Question

Swift - What is the best approach for managing Static Strings and Constants (like URLs, IDs, Image names etc)

Right now we are working with a flat file called Constants.swift with all the constants simply written there or inside a simple enum.
Is this a good approach? is there a better way (like saving a Plist or parsing an XML file)?

If Plists are the way to go, how do i read from them properly without making it overkill with a lot of code just to read from it?

Thanks

Answer

I think using an enum is a good approach, like this:

enum Constants {
    enum SubConstants {
        static let Constant1234 = "Hello sir!"
    }
}

and then use it like this:

print(Constants.SubConstants.Constant1234)

A plist could be a good approach if you have a server which gives you the constants depending on Country, users and so on.

If you want to use the plist you can follow this guide.

UPDATE:

How Adnan pointed out, you shouldn't use enum to store the constants since it is not a best practice, instead you should use a struct:

struct Constants {
    struct SubConstants {
        static let Constant1234 = "Hello sir!"
    }
}