Search code examples
swiftswiftuilocalization

How to create a localizable custom struct? (SwiftUI)


I have an Exercise.swift file where a struct is defined. Each element has an ID, name, instruction. Currently I'm trying to make my app localizable to support multiple languages. Usually I can just use the Localizable Strings file but if I add the name or instruction String there they won't get replaced as they should. Normal Text() and Button() elements are working fine. Is it somehow possible to replace Strings in a custom struct by the localized text?

I'm using the latest Xcode and iOS version as well as the SwiftUI framework.

Exercise file:

struct Exercise: Identifiable {
let id = UUID()
let name: String
let instruction: String
}

struct ExerciseList {
    static let allExercises = [
        Exercise(name: "name1",
                 instruction:  "instruction1"),
        Exercise(name: "name2",
                 instruction:  "instruction2")
    ]
}

What I've tried (Localizable file):

"name1" = "translation1";
"instruction1" = "translation2";
"name2" = "translation3";
"instruction2" = "translation4";

Solution

  • It is possible to use NSLocalizedString, like

    Exercise(name: NSLocalizedString("name1", comment: ""),
             instruction: NSLocalizedString("instruction1", comment: "")),
    

    if strings not in main app bundle, then see NSLocalizedString interface of how to specify needed bundle.