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?