I have been looking to translate my app into several foreign languages. After working with a Localizable String
file for a while, I have noticed that the expense category names
stored in a class aren't translated. Is there an alternate way to store these names and associated data so that the names can be translated? This isn't a static list of categories, but an active list from which the user may choose which category names they want to use within the app.
In other places within my app, I have used the format:
let EnterAddr = String(localized: "Enter Address")
Is it possible to use a variation of this in my class?
@MainActor
@Observable final class CategoryModel {
var catItem = [
Category(catNum: 0, catName: "Lodging", catBudget: 0, catPix: "bed.double.fill", catInUse: false, catCustom: false),
Category(catNum: 1, catName: "Food", catBudget: 0, catPix: "cart", catInUse: false, catCustom: false),
Category(catNum: 2, catName: "Airfare", catBudget: 0, catPix: "airplane", catInUse: false, catCustom: false),
...
There are a few options
The one that I use the most is to install this library SwiftUIX since I end up using few more functionality from that library and you could do smth link this
Category(catNum: 2, catName: LocalizedStringKey("Airfare").SwiftUIX_string, catBudget: 0, catPix: "airplane", catInUse: false, catCustom: false)
You could even go one step further and write a extension like so
extension String {
func translate() -> String {
return LocalizedStringKey(self)._SwiftUIX_string
}
}
// Usage
Category(catNum: 2, catName: "Airfare".translate(), catBudget: 0, catPix: "airplane", catInUse: false, catCustom: false)
Without any dependencies you can use the NSLocalizedString
Category(catNum: 2, catName: NSLocalizedString("Airfare", comment: ""), catBudget: 0, catPix: "airplane", catInUse: false, catCustom: false)
And like before you can simplify your life by adding a extension
extension String {
func translate(comment: String = "") -> String {
return NSLocalizedString(self, comment: comment)
}
}
// Usage
Category(catNum: 2, catName: "Airfare".translate(), catBudget: 0, catPix: "airplane", catInUse: false, catCustom: false)
Both these options should work anywhere in your app