Search code examples
iosswiftnsstringdefault-valuelocalizable.strings

Localizable strings and default values


I have a struct for my local notifications, with an init that goes into localizable.strings and assigns the value corresponding to key to the body of the notification:

struct Notification {
    let identifier: String
    let body: String

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

So if my localizable.strings looks like this:

"testKey" = "Test Notification";

Then initializing a new Notification object will yield the following:

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

However, if I initialize the notification with a typo, the body is just going to be the mistyped key:

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

My desired behaviour is to have a default string be assigned to the body of the notification if the initializer is called with a key that does not currently exist in localizable.strings, as below:

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

I know this can be achieved using one of the NSLocalizedString initializers, but in doing so, I would give up the benefits of using NSString.localizedUserNotificationString, which I don't want to do. Is there any way to achieve my desired behaviour without tapping into NSLocalizedString?


Solution

  • When there is no key/value for the string in defaults , it returns the same string you specify so if they are equal that means you can specify a default value

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