【问题标题】:Localizable strings and default values可本地化的字符串和默认值
【发布时间】:2019-10-03 20:56:06
【问题描述】:

我有一个用于本地通知的 struct,其中有一个 init 进入 localizable.strings 并将对应于 key 的值分配给通知:

struct Notification {
    let identifier: String
    let body: String

init(withKey: String) {
    self.id = key
    self.body = NSString.localizedUserNotificationString(forKey: key, arguments: nil)
}

所以如果我的 localizable.strings 看起来像这样:

"testKey" = "Test Notification";

然后初始化一个新的Notification 对象将产生以下结果:

let notification = Notification(withKey: "testKey")
print(notification.body)                        // prints "Test Notification"

但是,如果我用拼写错误初始化通知,则正文将成为输入错误的键:

let mistypedNotification = Notification(withKey: "tstKey")
print(mistypedNotification.body)                 // prints "tstKey"

我希望的行为是,如果使用 localizable.strings中当前不存在的键调用初始化程序,则将 default 字符串分配给通知正文>,如下:

let desiredNotification = Notification(withKey: "keyNotCurrentlyInLocalizableFile")
print(desiredNotification.body)           // prints "default string"

我知道这可以使用NSLocalizedString 初始化器之一来实现,但这样做我会放弃使用NSString.localizedUserNotificationString 的好处,而我不想这样做。有什么方法可以在不利用NSLocalizedString 的情况下实现我想要的行为?

【问题讨论】:

  • 测试您的代码并避免这种极端情况。不要进行本应在设计期间进行的不必要的运行时检查。
  • 文档说:“如果找不到与指定键对应的字符串资源,则返回的字符串为空。”——这似乎太错误了。

标签: ios swift nsstring default-value localizable.strings


【解决方案1】:

当 defaults 中的字符串没有键/值时,它会返回您指定的相同字符串,因此如果它们相等,则意味着您可以指定默认值

let possibleBody =  NSString.localizedUserNotificationString(forKey: key, arguments: nil) 
self.body = possibleBody == key ? "defaultValue" : possibleBody

【讨论】:

    【解决方案2】:

    @Sh_Khan 提出的解决方案有一个小缺点。如果您在创建通知时没有用户首选语言之一的翻译,则将显示默认值。如果以后的用户添加了您的应用支持的新语言,现有通知将不会调整其字符串,因为它应该与 localizedUserNotificationString 一起使用。

    遗憾的是,Apple 似乎不支持为本地化通知字符串提供默认值的直接方式,就像它为普通本地化字符串提供的那样。

    我建议尽可能使用您的默认值作为通知的键。在不可能的地方使用@Sh_Khan 的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多