How does one make an optional closure in swift?

前端 未结 4 2192
悲&欢浪女
悲&欢浪女 2020-11-30 00:32

I\'m trying to declare an argument in Swift that takes an optional closure. The function I have declared looks like this:

class Promise {

 func then(onFulfi         


        
相关标签:
4条回答
  • 2020-11-30 00:45

    Since I assume, that this "optional" closure should simply do nothing, you could use a parameter with an empty closure as default value:

    func then(onFulfilled: ()->(), onReject: ()->() = {}){       
        // now you can call your closures
        onFulfilled()
        onReject()
    }
    

    this function can now be called with or without the onReject callback

    then({ ... })
    then({ ... }, onReject: { ... })
    

    No need for Swift's awesome Optionals? here!

    0 讨论(0)
  • 2020-11-30 00:54

    Maybe it's a cleaner way. Specially when the closure has complicated parameters.

    typealias SimpleCallBack = () -> ()
    
    class Promise {
    
    func then(onFulfilled: SimpleCallBack, onReject: SimpleCallBack?){       
        if let callableRjector = onReject {
            // do stuff! 
        }
    }
    
    }
    
    0 讨论(0)
  • 2020-11-30 00:56

    You should enclose the optional closure in parentheses. This will properly scope the ? operator.

    func then(onFulfilled: ()->(), onReject: (()->())?){       
        if let callableRjector = onReject {
          // do stuff! 
        }
     }
    
    0 讨论(0)
  • 2020-11-30 00:59

    To make the code even shorter we can use nil as default value for onReject parameter and optional chaining ?() when calling it:

    func then(onFulfilled: ()->(), onReject: (()->())? = nil) {
      onReject?()
    }
    

    This way we can omit onReject parameter when we call then function.

    then({ /* on fulfilled */ })
    

    We can also use trailing closure syntax to pass onReject parameter into then function:

    then({ /* on fulfilled */ }) {
      // ... on reject
    }
    

    Here is a blog post about it.

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