Harshil.Chokshi Harshil.Chokshi - 3 years ago 131
Swift Question

How to pass in a nil type into a paramter in Swift?

I am converting an iOS app from objective-c to 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.

AlertViewShow(APPNAME, INTERNET_NOT, nil);

The nil is passed in for a UIAlertViewDelegate type. Now when converting it to Swift I cannot do

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".

How do I pass in nil into the parameter in Swift 2.0? Or is there another alternative besides passing in nil?

Answer Source

You need to make the argument itself take an optional value, rather than trying to force unwrap a nil optional (which will always crash).

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.

-(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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download