skip to Main Content

I’m currently building an app that is going to have Localization. This is a new topic for me and I’m struggling to find an efficient way of handling it. Typically we’d put our strings in Localizable.strings and then anywhere we need to use them we’d use something like NSLocalized("someKey", comment: "") however I feel like there’s a much better way to do this and to keep them organized, I just don’t know what that method is yet. Here’s what I’ve done so far.

Localizable.strings

"someKey1" = "Hello World";
"someKey2" = "Hello StackOverflow";

StringConstants.swift

enum AlertStrings {
    case ok
    case cancel
}

enum HelloStrings {
    case world
    case stackOverflow

    func getString() -> String {
        var stringValue = ""
        switch self {
            case .world
                stringValue = "someKey1"
            case .stackOverflow:
                stringValue = "someKey2"
        }

        return NSLocalizedString(stringValue, comment: "")
    }

Now with this type of setup, I can simply get my strings, without having to remember keys, by doing HelloStrings.world.getString() or HelloStrings.stackOverflow.getString(). This works, however, there’s quite a bit of setup that goes into this for each and every string value that I use. Is there a better way? I’d love to be able to just use something like HelloStrings.world but I suspect that’s not possible.

2

Answers


  1. For iOS you would like to use a default .strings files with NSLocalizedString macro.

    // Localizable.strings (file with your strings)
    "welcome_sceen_title" = "Welcome";
    "login_button" = "Log in";
    
    // Use in code
    NSLocalizedString("welcome_sceen_title", comment: "")
    

    Here is a full tutorial:
    https://lokalise.com/blog/getting-started-with-ios-localization/

    Login or Signup to reply.
  2. public enum HelloStrings: String {
        case world = "someKey1"
        case stackOverflow = "someKey2"
    
        var localized: String {
            return NSLocalizedString(self.rawValue, comment: "")
        }
    }
    

    HelloStrings.stackOverflow.localized

    If you use SwiftUI :

    import SwiftUI
    
    public enum HelloStrings: LocalizedStringKey {
        case world = "someKey1"
        case stackOverflow = "someKey2"
    
        var localized: LocalizedStringKey {
            return rawValue
        }
    }
    

    Text(HelloStrings.world.localized)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search