通过枚举、结构或其他方式处理本地化字符串?

Handle Localized Strings via Enum, Struct, or Other?

我目前正在构建一个将具有本地化功能的应用程序。这对我来说是一个新话题,我正在努力寻找一种有效的方法来处理它。通常我们会把我们的字符串放在 Localizable.strings 中,然后在我们需要使用它们的任何地方我们会使用类似 NSLocalized("someKey", comment: "") 的东西,但是我觉得有更好的方法来做到这一点并使它们井井有条,我只是不知道那个方法是什么。这是我到目前为止所做的。

Localizable.strings

"someKey1" = "Hello World";
"someKey2" = "Hello Whosebug";

StringConstants.swift

enum AlertStrings {
    case ok
    case cancel
}

enum HelloStrings {
    case world
    case Whosebug

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

        return NSLocalizedString(stringValue, comment: "")
    }

现在,通过这种设置,我可以通过 HelloStrings.world.getString()HelloStrings.Whosebug.getString() 简单地获取我的字符串,而无需记住键。这是有效的,但是,对于我使用的每个字符串值,都有相当多的设置。有没有更好的办法?我希望能够只使用 HelloStrings.world 之类的东西,但我怀疑那是不可能的。

对于 iOS,您希望使用带有 NSLocalizedString macro.

的默认 .strings 文件
// Localizable.strings (file with your strings)
"welcome_sceen_title" = "Welcome";
"login_button" = "Log in";

// Use in code
NSLocalizedString("welcome_sceen_title", comment: "")

这里是一个完整的教程: https://lokalise.com/blog/getting-started-with-ios-localization/

public enum HelloStrings: String {
    case world = "someKey1"
    case Whosebug = "someKey2"

    var localized: String {
        return NSLocalizedString(self.rawValue, comment: "")
    }
}

HelloStrings.Whosebug.localized

如果你使用 SwiftUI :

import SwiftUI

public enum HelloStrings: LocalizedStringKey {
    case world = "someKey1"
    case Whosebug = "someKey2"

    var localized: LocalizedStringKey {
        return rawValue
    }
}

Text(HelloStrings.world.localized)