cristainlika3
cristainlika3

Reputation: 299

How can I make a nil compatible completion handler?

I created a function with a completion handler. Sometimes I need to use the completion block, sometimes not.

Here is the function:

func numberCheck(number: String , completion : @escaping (Bool)->()){
     //some task do here 
    completion(true)
}

use:

numberCheck(number: "77" , completion: {_ in
    //some task do here 
})

But I want to leave it completion block nil:

numberCheck(number: "77" ,  completion: nil)

but it is gives me an error:

Nil is not compatible with expected argument type '(Bool) -> ()'

Upvotes: 3

Views: 3345

Answers (2)

henrique
henrique

Reputation: 1112

Just make your closure parameter optional like:

func numberCheck(number: String, completion: @escaping ((Bool)->())?)

Also, you can set a default value like:

func numberCheck(number: String, completion: @escaping ((Bool)->())? = nil)

This way you can call without informing nil to the completion parameter, simply:

numberCheck(number: "123")

Upvotes: 1

vadian
vadian

Reputation: 285290

Make the closure optional

func numberCheck(number: String , completion : @escaping ((Bool)->())?){

or for better readability

typealias CheckResult = (Bool)->()

func numberCheck(number: String , completion : @escaping CheckResult? ){

But then you have to write in the body of the function

completion?(true)

Upvotes: 9

Related Questions