XLFormDescriptor initialize with Title in Swift

193 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

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)