Search code examples
iosios7swift

type 'String' does not conform to protocol 'NilLiteralConvertiblle'


this line of Code:

var errorView = UIAlertView(title: errorTitle, message: errorString, delegate:self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK", nil)

rewritten from Objective-C Code:

 UIAlertView *errorView =
        [[UIAlertView alloc] initWithTitle:errorTitle
            message:errorString delegate:self cancelButtonTitle:nil
            otherButtonTitles:@"OK", nil];

which gives me this error:

type 'String' does not conform to protocol 'NilLiteralConvertiblle'

I can fix it by not putting nil in the end, but I just don't know why, does somebody know the answer?


Solution

  • It's a Variadic Parameter which required nil termination in Objective-C, but doesn't in Swift.

    Swift method signature:

    init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
    

    Objective-C method signatire:

    - (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION 
    

    Technically, it's the moreButtonTitles that is the variadic parameter in Swift.