swift中具有本地化字符串的枚举

zazmityj  于 2022-11-21  发布在  Swift
关注(0)|答案(7)|浏览(184)

我想用枚举处理本地化的字符串,所以我这样做,它工作正常,但这个解决方案的问题是:我不能轻易地从本地化的字符串中获取枚举值,我必须有密钥才能做到这一点:

let option = DietWithoutResidueOption(rawValue: "NoDiet")

如果不是,我必须调用dietWithoutResidueOptionWith方法来获取枚举值...:/
有更好的解决方案直接存储localizedString而不是枚举中的键吗?
谢谢

枚举

enum DietWithoutResidueOption: String {
  case NoDiet = "NoDiet"
  case ThreeDays = "ThreeDays"
  case FiveDays  = "FiveDays"

  private func localizedString() -> String {
    return NSLocalizedString(self.rawValue, comment: "")
  }

  static func dietWithoutResidueOptionWith(#localizedString: String) -> DietWithoutResidueOption {
    switch localizedString {
    case DietWithoutResidueOption.ThreeDays.localizedString():
      return DietWithoutResidueOption.ThreeDays
    case DietWithoutResidueOption.FiveDays.localizedString():
      return DietWithoutResidueOption.FiveDays
    default:
      return DietWithoutResidueOption.NoDiet
    }
  }
}

可本地化的. string

"NoDiet" = "NON, JE N'AI PAS DE RÉGIME";
"ThreeDays" = "OUI, SUR 3 JOURS";
"FiveDays"  = "OUI, SUR 5 JOURS";

打电话

println(DietWithoutResidueOption.FiveDays.localizedString())
1tuwyuhd

1tuwyuhd1#

试试这个,它非常简单直接:

enum ChoicesTitle: String {
    case choice1 = "Choice 1"
    case choice2 = "Choice 2"
    case choice3 = "Choice 3"
    case choice4 = "Choice 4"
    case choice5 = "Choice 5"
    case choice6 = "Choice 6"
    
    func localizedString() -> String {
        return NSLocalizedString(self.rawValue, comment: "")
    }
    
    static func getTitleFor(title: ChoicesTitle) -> String {
        return title.localizedString()
    }
}

您可以这样使用它:

let stringOfChoice1: String = ChoicesTitle.getTitleFor(title: .choice1)

希望这对你有用

p5fdfcr1

p5fdfcr12#

您可以将任何StringLiteralConvertible, Equatable类型用于enumRawValue类型。
那么,怎么样:

import Foundation

struct LocalizedString: StringLiteralConvertible, Equatable {

    let v: String

    init(key: String) {
        self.v = NSLocalizedString(key, comment: "")
    }
    init(localized: String) {
        self.v = localized
    }
    init(stringLiteral value:String) {
        self.init(key: value)
    }
    init(extendedGraphemeClusterLiteral value: String) {
        self.init(key: value)
    }
    init(unicodeScalarLiteral value: String) {
        self.init(key: value)
    }
}

func ==(lhs:LocalizedString, rhs:LocalizedString) -> Bool {
    return lhs.v == rhs.v
}

enum DietWithoutResidueOption: LocalizedString {
    case NoDiet = "NoDiet"
    case ThreeDays = "ThreeDays"
    case FiveDays  = "FiveDays"

    var localizedString: String {
        return self.rawValue.v
    }

    init?(localizedString: String) {
        self.init(rawValue: LocalizedString(localized: localizedString))
    }
}

使用此方法,可以通过3种方式构造DietWithoutResidueOption

let option1 = DietWithoutResidueOption.ThreeDays
let option2 = DietWithoutResidueOption(rawValue: "ThreeDays") // as Optional
let option3 = DietWithoutResidueOption(localizedString: "OUI, SUR 3 JOURS")  // as Optional

并使用以下命令提取本地化字符串:

let localized = option1.localizedString
r7s23pms

r7s23pms3#

这是一个迟来的答案,但我刚刚与苹果工程师就他们推荐的主题进行了交谈:

enum LocalizedStrings {
        case title

        var localized: String {
            switch self {
            case .title:
                return NSLocalizedString("My Title", comment: "My Comment")
            }
        }
    }

在您的情况下,解决方案与原始代码没有太大区别:

enum DietWithoutResidueOption {
        case NoDiet
        case ThreeDays
        case FiveDays

        var localizedString: String {
            switch self {
            case .NoDiet:
                return NSLocalizedString("NoDiet", comment: "Some comment")
            case .ThreeDays:
                return NSLocalizedString("ThreeDays", comment: "Some comment")
            case .FiveDays:
                return NSLocalizedString("FiveDays", comment: "Some comment")
            }
        }

        static func dietWithoutResidueOptionWith(localizedString: String) -> DietWithoutResidueOption {
            switch localizedString {
            case DietWithoutResidueOption.ThreeDays.localizedString:
                return DietWithoutResidueOption.ThreeDays
            case DietWithoutResidueOption.FiveDays.localizedString:
                return DietWithoutResidueOption.FiveDays
            default:
                return DietWithoutResidueOption.NoDiet
            }
        }
    }

原因是他们不想让你把变量传递给NSLocalizedString()。这与优化和解析字符串有关。想象一下,Xcode在某个时候自己生成了可本地化的.strings文件,但它找不到字符串,因为它们是作为变量传递的。

piv4azn7

piv4azn74#

一个不错的方法是使用静态变量创建一个可本地化字符串的结构,如下所示:

本地化字符串.swift

struct LocalizableStrings {
    static let noDiet  = NSLocalizedString("NoDiet", comment: "")
    static let threeDays  = NSLocalizedString("ThreeDays", comment: "")
    static let fiveDays  = NSLocalizedString("FiveDays", comment: "")
}

可本地化的. string

"NoDiet" = "NON, JE N'AI PAS DE RÉGIME";
"ThreeDays" = "OUI, SUR 3 JOURS";
"FiveDays"  = "OUI, SUR 5 JOURS";

您的枚举将如下所示:

枚举

enum DietWithoutResidueOption {
    case NoDiet,
    ThreeDays,
    FiveDays

    var description : String {
        get {
            switch(self) {
            case .NoDiet:
                return LocalizableStrings.noDiet
            case .ThreeDays:
                return LocalizableStrings.threeDays
            case .FiveDays:
                return LocalizableStrings.fiveDays
            }
        }
    }
}

因此,例如,要获得你的描述,你可以这样做:

DietWithoutResidueOption.NoDiet.description

这种方法的好处是将可本地化字符串的键放在一个文件中。因此,例如,如果更改Localizable.strings文件中的 NoDiet 键,只需更新LocalizableStrings.swift文件,而不是将 NoDiet 键作为字符串的所有位置。此外,你要冒着在某个文件中拼写错误 NoDiet 键的风险,而你的代码在编译时不会出错,同时使用LocalizableStrings.swift中的一个静态变量,你可以避免这种情况,因为您的代码将无法编译,并且您将看到一条错误消息,指出错误所在。

5jdjgkvh

5jdjgkvh5#

另一种选择:

枚举

enum Title : String {

  case CEO = "CEOKey"
  case CTO = "CTOKey"
  case CFO = "CFOKey"

  private static let allTitles = [CEO, CTO, CFO]

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

  init!(rawValue: String) {
    var keys =  Title.allTitles
    var filtered = keys.filter { $0.rawValue == rawValue }

    self = filtered.first!
  }

  init!(localizedString: String) {
    var keys =  Title.allTitles
    var filtered = keys.filter { $0.localizedString == localizedString }

    self = filtered.first!
  }
}

可本地化的. string

"CEOKey" = "Chief Executive Officer";
"CTOKey" = "Chief Technical Officer";
"CFOKey" = "Chief Financial Officer";

压缩枚举:

let option1 = Title.CFO
let option2 = Title(rawValue: "CTOKey") // init from key
let option3 = Title(localizedString: NSLocalizedString("CEOKey", comment: ""))  // init from value

提取本地化字符串:

println("option1 localized string : \(option1.localizedString)")
println("option2 localized string : \(option2.localizedString)")
println("option3 localized string : \(option3.localizedString)")

输入

option1 localized string : Chief Financial Officer
option2 localized string : Chief Technical Officer
option3 localized string : Chief Executive Officer

如果找不到本地化字符串或键,此代码将生成异常

vlju58qv

vlju58qv6#

这是我的例子

enum Localization: String {
    case appName = "app_name"
    case appOk = "app_ok"
    case appError = "app_error"
    case placeholderNoContent = "placeholder_no_content"
    case homeTitle = "home_title"

public func localized(args: CVarArg...) -> String {
    let localizedString = NSLocalizedString(self.rawValue, comment: "")
    return withVaList(args, { (args) -> String in
        return NSString(format: localizedString, locale: Locale.current, arguments: args) as String
    })
}
}

用途

self.homeTitleLabel = Localization.homeTitle.localized()

此本地化枚举可以轻松地与字符串格式一起使用。

ryevplcw

ryevplcw7#

试试我创建的这个协议,你可以导入,使用它如下.
https://github.com/Wei18/ZWExt/blob/master/ZWExt/Classes/Protocol/Localizable.swift

enum SomeKey: String, Localizable {
  case MenuGreeting = "lb_menu_greeting"
  case HaveBook = "I have %@ books"
}

// Sample
let menuGreeting: String = SomeKey.MenuGreeting.localized()
let iHaveBoxes: String = SomeKey.HaveBook.localized([3])

/*
// You also can make it with html.
SomeKey.CustomCase.localizedHTML()
SomeKey.CustomCase.localizedHTML([])
*/

相关问题