我有这样的枚举:
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/