Passing optional callback into Swift function

前端 未结 3 784
野性不改
野性不改 2021-02-01 01:06

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

func dismiss(completion: () -> Void) {
    if (completion) {
        ret         


        
相关标签:
3条回答
  • 2021-02-01 01:35

    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.

    0 讨论(0)
  • 2021-02-01 01:39

    Just adding to Martin R's answer above..

    The callback can be optional, instead of implicit parameter (with exclamation mark), use the optional operator.

    func dismiss(completion: (() -> Void)?) {
        if completion != nil {
            return self.dismissViewControllerAnimated(true, completion: completion!)
        }
    
        self.dismissModalViewControllerAnimated(true)
    }
    
    0 讨论(0)
  • 2021-02-01 01:40

    It's better to add = nil in the callback declaration, to avoid passing nil while calling it:

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

    And you can call your function like this : dismiss()

    0 讨论(0)
提交回复
热议问题