Nowadays we feel much comfortable using Enum when apple gives CaseIterable protocol through which we can iterate enum cases like an Array. How to use CaseIterable protocol with a raw value:-
1 2 3 4 5 |
enum Test: String, CaseIterable { case test = "Test" case test1 = "Test1" case test2 = "Test2" } |
Get an array of all cases:-
1 2 3 4 5 |
print(Test.allCases) // For getting raw values print(Test.allCases[0].rawValue) |
Many of the times we needed to use the raw value as display strings on labels and buttons etc. If the app contains localization it makes difficult to deal with actual localized string in enum cases and for we write multiple strings lines of code again and again. if we directly localized the raw value then gets an error “Raw value for enum case must be a literal”
1 2 3 4 5 |
enum Test: String, CaseIterable { case test = NSLocalizedString("Test", comment: "") // this line give an error "Raw value for enum case must be a literal" case test1 = "Test1" case test2 = "Test2" } |
so have just take a look deal with localized raw value:-
1 2 3 4 5 6 7 8 9 |
enum Test: String, CaseIterable { case test = "Test" case test1 = "Test1" case test2 = "Test2" func localizedString() -> String { return NSLocalizedString(self.rawValue, comment: "") } } |
How to use them:-
1 |
print(Test.allCases[0].rawValue.localizedString()) |
I hope from this, it will make you more comfortable dealing with Localized String of enum. Thanks for tuning in once again!