How to translate / localize a variable in Swift

Viewed 357

I have this code and I have localization setup successfully. I created a Categories.strings file and localized it, but the translation of the categories is not working.

Code:

struct CategoriesViewRow: View {
    var selection: SimpleJson

    var body: some View {
        HStack {
            Image(selection.name)
                .resizable()
                .scaledToFit()
                .frame(width: 20, height: 20)
            Text(String(localized: "\(selection.name)", table: "Categories", comment: "Category"))
            Spacer()
        }
    }
}

This var selection: SimpleJson is a struct that looks like this:

struct SimpleJson: Hashable, Codable, Identifiable {
    var id: Int
    
    var name: String
    var description: String?
    var hidden: Bool?
}

It contains some static categories loaded from a file. They need to be loaded from the file, and I always managed to translate them in Objective-C. But now in Swift, it seems like I am missing something.

Normal SwiftUI Text() code gets translated correctly, but with my other code, there is something wrong.

I am currently using Xcode Beta 13.0, but I am quite sure this isn't the problem. I rather think I am doing something wrong, but I can't seem to find some good info for my use-case.

Can someone help me out?

Thanks in advance

1 Answers

You can add this function to a String extension and then call .localize() on string variables:

extension String {
    /**
     So that when you return a String it also adjusts the language
     - Parameter comment: To describe specific meaning if it's unclear (e.g.: bear could mean the animal or the verb to bear)
     - Returns: The localized String duh
     - Usage: str.localize()
     - Further reading: https://www.hackingwithswift.com/example-code/uikit/how-to-localize-your-ios-app
     */
    func localize(comment: String = "") -> String {
        NSLocalizedString(self, comment: comment)
    }
}
Related