Kosmetika Kosmetika - 6 months ago 102
Swift Question

Passing optional callback into Swift function

I'm learning Swift lang, but I cannot pass optional callback argument into function:

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


This shows me an error -
Type () -> Void does not conform to protocol 'LogicValue'


Any suggestions?

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.

Comments