1

Why this works OK:

let formFescriptor = XLFormDescriptor(title: "Sign Up");

And this:

let formFescriptor = XLFormDescriptor(title: NSLocalizedString("Sign Up", comment: nil));

Gives me error:

Cannot invoke initializer for type 'XLFormDescriptor' with an argument list of type '(title: String)'

Why?

orkenstein
  • 2,810
  • 3
  • 24
  • 45

2 Answers2

3

NSLocalizedString have non-optional comment, while you are passing nil into it. Change comment to something meaningful in a context, so NSLocalizedString will be initialized properly, as well as XLFormDescriptor.

Nikita Leonov
  • 5,684
  • 31
  • 37
  • 1
    Indeed! I didn't know about `= default` before)) `NSLocalizedString("Sign Up", comment: "")` works as well. – yas375 Aug 07 '15 at 22:30
3

Ib Objective-C NSLocalizedStringis a macros defined in NSBundle.h:

#define NSLocalizedString(key, comment) \
    [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]

In Swift it's a function:

func NSLocalizedString(key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -> String

You can use it as:

let title = NSLocalizedString("Sign Up", tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
let formDescriptor = XLFormDescriptor(title: title)

Or you can use equivalent code called from the macros:

let title = NSBundle.mainBundle().localizedStringForKey("Sign Up", value: nil, table: nil)
let formDescriptor = XLFormDescriptor(title: title)

Another nice idea is to add a nice method to String class to have nice syntax. Here is an example from this answer:

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
    }
}

And then use it like:

let formDescriptor = XLFormDescriptor(title: "Sign Up".localized)
Community
  • 1
  • 1
yas375
  • 3,940
  • 1
  • 24
  • 33