Search code examples
swiftiphonestringxcodelocalization

Handle Localized Strings via Enum, Struct, or Other?


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.


Solution

  • 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)