Localization with SwiftUI

    I have been performing a bit of localization lately on an Xcode project and was looking for a way to reduce human errors due to typos and other human errors.

    The best method I found was to create a separate a simple Translation.swift file to storage all the i18n code. Here I extend the LocalizedStringKey struct with my own project based localized strings for easy access on the Xcode autocomplete menu.

    import SwiftUI
    
    extension LocalizedStringKey {
        static var ourLocalizedProjectName: LocalizedStringKey {
            return "OurLocalizedProjectName"
        }
    }
    
    struct Translation: View {
        var key: LocalizedStringKey
    
        var body: some View {
            Text(self.key)
        }
    
        init(_ key: LocalizedStringKey) {
            self.key = key
        }
    }
    
    struct Translation_Previews: PreviewProvider {
        static var previews: some View {
            Translation(.mainFooterMessage)
                .environment(\.locale, .init(identifier: "en"))
        }
    }
    

    And add to your Localizable.strings file, strings that correspond to the keys in the extension created earlier.

    // Localized project strings
    "OurLocalizedProjectName" = "Project Name";
    

    Note, I don’t use the View anywhere in the project, other than to use it for previews in Xcode. I usually populate the view with translations and adjust the locale environment variable to see the different project translations.

    Happy translating and stay save in COVIDLand.

    Filed in: SwiftUI, iOS, macOS
    Reading Time: 1 minute(s)