Passing optional callback into Swift function

Update for Swift 3/4:

An optional is no longer a boolean expression, and the
deprecated func dismissModalViewControllerAnimated(animated: Bool)
is no longer available in Swift.

Simply declare the completion parameter as an optional closure, and
pass it on to

func dismiss(animated flag: Bool, completion: (() -> Void)? = nil)

which takes an optional closure as well:

func dismiss(completion: (() -> Void)? = nil) {
    self.dismiss(animated: true, completion: completion)
}

Old (Swift 1.x?) answer:

Declare the completion parameter as (implicitly unwrapped) optional closure (() -> Void)!:

func dismiss(completion: (() -> Void)!) {
    if (completion) {
        return self.dismissViewControllerAnimated(true, completion: completion)
    }
    self.dismissModalViewControllerAnimated(true)
}

But note that you can call

self.dismissViewControllerAnimated(true, completion: completion)

in any case, because the completion parameter of that function is optional as well.
And

func dismissModalViewControllerAnimated(animated: Bool)

is actually marked as deprecated.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)