简体   繁体   English

如何在Swift中将nil类型传递给参数?

[英]How to pass in a nil type into a paramter in Swift?

I am converting an iOS app from objective-c to swift. 我正在将iOS应用程序从Objective-C转换为Swift。 In the objective-c version of the app there was a method, AlertViewShow that gets called, and for one of its parameters nil was passed in like below. 在该应用程序的Objective-C版本中,有一个方法AlertViewShow被调用,并为其参数之一传递了nil,如下所示。

AlertViewShow(APPNAME, INTERNET_NOT, nil);

The nil is passed in for a UIAlertViewDelegate type. 为UIAlertViewDelegate类型传入nil。 Now when converting it to Swift I cannot do 现在将其转换为Swift时我无法做

AlertViewShow(APPNAME, INTERNET_NOT, nil) //error: cannot pass in nil into paramter

So, by looking at stack forums I tried this... 因此,通过查看堆栈论坛,我尝试了此方法...

let alertViewNilObject: UIAlertViewDelegate? = nil
AlertViewShow(APPNAME, INTERNET_NOT, alertViewNilObject!) //compiler doesnt complain

So no errors pop up. 因此没有错误弹出。 But when I run the app it says: "fatal error: unwrapped a nil value". 但是,当我运行该应用程序时,它说:“致命错误:解开了一个nil值”。

How do I pass in nil into the parameter in Swift 2.0? 如何在Swift 2.0中将nil传递给参数? Or is there another alternative besides passing in nil? 还是除了传递nil之外还有其他选择吗?

You need to make the argument itself take an optional value , rather than trying to force unwrap a nil optional (which will always crash). 您需要使参数本身具有一个可选值 ,而不是试图强制解开一个nil可选值(这将始终崩溃)。

func AlertViewShow(title:String, desc:String, delegate:AlertViewDelegate?) {

    if delegate != nil {
        // do some delegate-y things
    }

    ...
}

...

AlertViewShow(title: APPNAME, desc: INTERNET_NOT, delegate: nil)

If it's an obj-c method that you're not re-writing in Swift, you'll just have to add the nullable prefix to the argument. 如果您不是在Swift中重写的obj-c方法,则只需在参数中添加nullablenullable前缀即可。

-(void) AlertViewShow:(NSString*)title desc:(NSString*)description delegate:(nullable UIAlertViewDelegate*)delegate;

(although it's worth noting that method names should start with a lowercase, not an uppercase) (尽管值得注意的是方法名称以小写字母开头,而不是大写字母)

That should then get converted to an optional argument when bridging. 然后在桥接时应将其转换为可选参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM