0

I’m experimenting with passing functions as arguments, and am having trouble getting Swift to accept functions of a particular argument signature. I’ve created a kind of “container” class for method references that looks like this:

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) }  }

In my App class I declare an array of these:

@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.

And an experimental invocation might look something like:

    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")  }  
      }

Except that I haven’t gotten that far yet, because the first line in my thingsToDo array is always flagged red:

Cannot convert value of type '(MyApp) -> (Bool) -> Bool' to expected argument type '(Bool) -> Bool'

What am I doing wrong? I think I understand what a signature of the form (...) -> Type means, but (...) -> (...) -> Type is confusing me: something is handing a value of some Type to … some third thing?

Jeff J
  • 139
  • 8
  • Ok, I’ve been referred to a very thorough discussion of a similar question. So it looks like I’m asking a duplicate question. What’s the StackOverflow protocol? Do I delete my question? – Jeff J May 19 '17 at 19:19
  • Feel free just to leave the question as-is, as it's a useful signpost to the dupe target – compare [How should duplicate questions be handled?](https://meta.stackexchange.com/q/10841/314779) "*Having multiple copies of the same question with different wording is useful as search fodder, because people looking for an answer may use different wording too.*" – Hamish May 19 '17 at 19:34

0 Answers0