Skip to content

Instantly share code, notes, and snippets.

@Jegge
Last active February 5, 2023 19:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jegge/02bd8b298ea750e704c35a7f9f1b8c06 to your computer and use it in GitHub Desktop.
Save Jegge/02bd8b298ea750e704c35a7f9f1b8c06 to your computer and use it in GitHub Desktop.
Localized enums in Swift
"Test_a" = "AAAAA";
"Test_b" = "BBBBB";
"Test_c" = "CCCCC";
"Test_d" = "DDDDD";
enum Test: LocalizedStringConvertible {
case a, b, c, d
}
print(Test.a, Test.b, Test.c, Test.d)
// a b c d
print(Test.a.resourceKey, Test.b.resourceKey, Test.c.resourceKey, Test.d.resourceKey)
// Test_a Test_b Test_c Test_d
print(Test.a.localizedDescription, Test.b.localizedDescription, Test.c.localizedDescription, Test.d.localizedDescription)
// AAAAA BBBBB CCCCC DDDDD
import Foundation
protocol LocalizedStringConvertible {
var resourceKey: String { get }
var resourceComment: String { get }
var localizedDescription: String { get }
}
extension LocalizedStringConvertible {
var resourceKey: String {
return "\(String(describing: type(of: self)))_\(String(describing: self))"
}
var resourceComment: String {
return "Localization for value '\(String(describing: self))' in enum '\(String(describing: type(of: self)))'"
}
var localizedDescription: String {
return NSLocalizedString(resourceKey, comment: resourceComment)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment