Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 481
MarkosDarkin Avatar asked Dec 24 '22 02:12

MarkosDarkin


1 Answers

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!"
    }
}
like image 143
Marco Santarossa Avatar answered Feb 23 '23 00:02

Marco Santarossa