swiftxcodefoundation

How can we mark function parameters (string literals) as localisable?


I'm writing a convenience init for NSError.

extension NSError {
    public convenience init(domain: String = #file, code: Int = Int(#line), localizedDescription: String) {
        self.init(domain: domain, code: code, userInfo: [NSLocalizedDescriptionKey: localizedDescription])
    }
}

To create an error with localised description from string literal I now can do:

let localisedError = NSError(localizedDescription: NSLocalizedString("Some description that will be localized.", comment: "Comment for translator"))

Is there a way to pass literals directly to init (or any other func) in a way that will ensure that they will be automatically passed to translations that Xcode generates as it does for literals passed to NSLocalizedString(). So that I could just call

let localisedError = NSError(localizedDescription: "Some description that will be localized.")

Solution

  • If I understand correctly, you can just take a LocalizedStringResource. This is a Foundation type, and works correctly with string literals and string interpolations, just like LocalizedStringKey does.

    public convenience init(domain: String = #file, code: Int = Int(#line), localizedDescription: LocalizedStringResource) {
        self.init(domain: domain, code: code, userInfo: [
            NSLocalizedDescriptionKey: String(localized: localizedDescription)
        ])
    }