swift - 使用 R.Swift 库在 swift 中本地化枚举

标签 swift enums

我有这样的枚举:

enum Gender {
    case male
    case female

    func toString() -> String {
        switch self {
        case .male:
            return R.string.localizable.male()
        case .female:
            return R.string.localizable.female()
        }
    }
}

enum Relationship {
    case mother
    case father
    case son
    case daughter
    case brother
    case sister
    case grandmother
    case grandfather
    case grandson
    case granddaugther
    case aunt
    case uncle
    case cousin
    case stepsister
    case stepbrother
    case grandgrandmother
    case grandgrandfather
    case other
}

是否有更简单的方法来本地化枚举字符串值?对于像第一个这样的小枚举,这不是问题,但对于第二个更长的枚举,这会增加更多的代码行。

在这种情况下,也许有一些更简单的方法来创建可本地化的字符串描述?

我也尝试过:

enum Gender: String {
    case male = R.string.localizable.male()
    case female
}

但这会导致编译器错误(这里需要纯文字)

最佳答案

使枚举符合RawRepresentable是一种合适的方法,只需本地化原始值即可

enum Gender : String {
    case male
    case female

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

关于swift - 使用 R.Swift 库在 swift 中本地化枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55975785/

相关文章:

java 枚举 - 在其他 java 文件中使用时不编译

java - Hibernate 要求 javax.validation.constraints.Size 进行枚举

swift - 如何使用 swift 3 和 iOS 10 将 zip 文件上传到 FTP 服务器?

ios - 不能在 inout 函数中使用 SKShapeNode

c# - 准备枚举列表并从 List<enum> 中找到一个枚举值

c++ - 需要 C++ 中的枚举类型转换解释

c# - IValueConverter 删除 enum(int) 的基础值

ios - 如何在 iOS 10 中自动调整包含文本的 Collection View 单元格的大小

ios - 每次呈现时查看 Controller 原点更改

java - 如何安排具有初始延迟的计时器?