Leem
Leem

Reputation: 18298

Pass a closure as an optional parameter of the function

I have a function which takes two parameters, the last parameter is a callback closure:

func myAsycTask(name: String, callback: @escaping ()->Void) {
   myQueue.async{
      self.doTask(name)
      callback()
   }
} 

func doTask(name: String) {...}

I would like to make the 2nd callback closure parameter optional. I tried to re-define the function above to:

func myAsycTask(name: String, callback: @escaping ()->Void? = nil) {
       myQueue.async{
          self.doTask(name)
          callback()
       }
} 

I get a compiler error:

Nil default argument value of cannot be converted to type '() ->'

How can I achieve what I need then?

Upvotes: 5

Views: 1675

Answers (2)

Oleh Zayats
Oleh Zayats

Reputation: 2443

Try making your callback closure Optional and remove @escaping. @escaping annotation is pointless because your parameter is basically an enum (Optional is an enum with 2 cases: some(Value) and none) If your closure is owned by another type it is implicitly escaping.

import UIKit

// Also you can use a typealias to keep code more readable
typealias Callback = (() -> Void)

class Test {

    let myQueue = DispatchQueue(label: "com.playground")

    func doTask(name: String) {
        // something...
    }

    func myAsycTask(name: String, callback: Callback? = nil) {
        myQueue.async { [weak self] in
            self?.doTask(name: name)
            callback?()
        }
    }
}

Upvotes: 2

user3151675
user3151675

Reputation: 58029

Your current code means that Void is an optional return in the closure (which does not make much sense, since Void is already nothing). You should enclose the parameter in brackets and then make it optional.

func myAsycTask(name: String, callback: (() -> Void)? = nil)

Upvotes: 5

Related Questions