【发布时间】: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