【问题标题】:type 'String' does not conform to protocol 'NilLiteralConvertiblle'类型“字符串”不符合协议“NilLiteralConvertiblle”
【发布时间】:2014-09-19 22:38:14
【问题描述】:

这行代码:

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

从 Objective-C 代码重写:

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

这给了我这个错误:

类型“字符串”不符合协议“NilLiteralConvertiblle”

我可以通过不在最后加上 nil 来解决它,但我只是不知道为什么,有人知道答案吗?

【问题讨论】:

    标签: ios ios7 swift


    【解决方案1】:

    这是一个 Variadic Parameter,它在 Objective-C 中需要 nil 终止,但在 Swift 中不需要。

    Swift 方法签名:

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

    Objective-C 方法签名:

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

    从技术上讲,moreButtonTitles 是 Swift 中的可变参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多