How does one make an optional closure in swift?

前端 未结 4 2218
悲&欢浪女
悲&欢浪女 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!

提交回复
热议问题