传递闭包作为函数的可选参数

时间:2021-12-14 11:09:06

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 '() ->'

Nil默认参数值不能转换为'( - ) - >'

How can I achieve what I need then?

我怎样才能实现我所需要的呢?

2 个解决方案

#1


5  

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.

您当前的代码意味着Void是闭包中的可选返回(这没有多大意义,因为Void已经没有了)。您应该将参数括在括号中,然后使其成为可选参数。

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

#2


0  

Try making your callback closure Optional and remove @escaping:

尝试使你的回调闭包可选并删除@escaping:

import UIKit

// Also you can use a type alias 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?()
        }
    }
}

#1


5  

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.

您当前的代码意味着Void是闭包中的可选返回(这没有多大意义,因为Void已经没有了)。您应该将参数括在括号中,然后使其成为可选参数。

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

#2


0  

Try making your callback closure Optional and remove @escaping:

尝试使你的回调闭包可选并删除@escaping:

import UIKit

// Also you can use a type alias 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?()
        }
    }
}