在Swift中将函数作为参数传递时,参数签名有问题

时间:2017-05-19 18:16:47

标签: swift parameter-passing method-signature

我正在尝试将函数作为参数传递,并且无法让Swift接受特定参数签名的函数。我为方法引用创建了一种“容器”类,如下所示:

public class Job  { 
    let name: String, method: (Bool) -> Bool

    init (name: String, method: @escaping (Bool) -> Bool)
      { self.name = name;  self.method = method }

    func doNow (_ now: Bool) -> Bool
      { return  method(now) }  }

在我的App类中,我声明了一个这样的数组:

@NSApplicationMain

public class MyApp : NSApplicationDelegate  {

    let thingsToDo = [
        Job.init(name: "This", method: doThis),
        Job.init(name: "That", method: doThat),
        Job.init(name: "Other Thing", method: doOther) ]

    func doThis(_ now: Bool) -> Bool  {
        var done = now
        //  Do stuff conditionally.
        return done    }

    //  doThat and doOther are similar: Bool result from one Bool argument.

实验性调用可能类似于:

    public func applicationDidFinishLaunching (_ notice: Notification)  { 
        let now = true  //  or false: just an exercise at the moment.
        for job in thingsToDo  {
            let done = job.doNow(now)
            NSLog ("%@ was %@.", job.name, done ? "done" : "not done")  }  
      }

除了我还没有那么远,因为我的thingsToDo数组中的第一行总是标记为红色:

  

无法转换类型'(MyApp)的值 - > (布尔) - >布尔'预期参数类型'(Bool) - >布尔'

我做错了什么?我想我理解(...) -> Type形式的签名是什么意思,但(...) -> (...) -> Type令我感到困惑:有些东西正在将某种类型的值交给......第三件事?

0 个答案:

没有答案