I'm a swift beginner, so be gentle...
I'm having trouble assigning a function as a parameter.
I have defined this struct:
struct dispatchItem {
let description: String
let f: ()->Void
init(description: String, f: @escaping ()->()) {
self.description = description
self.f = f
}
}
I make use of this within a class called MasterDispatchController
like so:
class MasterDispatchController: UITableViewController {
let dispatchItems = [
dispatchItem(description: "Static Table", f: testStaticTable),
dispatchItem(description: "Editable Table", f: testEditableTable)
]
func testEditableTable() {
//some code
}
func testStaticTable() {
//some code
}
etc.
Then I have a table view in my code that dispatches out to whichever function was clicked on (there are more than just the two I showed in the code above, but that's unimportant) like so
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dispatchItems[indexPath.row].f()
}
So... The compiler is not happy with this. It says when I am defining the dispatchItems let statement:
Cannot convert value of type '(MasterDispatchController) -> () -> ()' to expected argument type '() -> ()'
I figure... ok... I'm not sure I exactly understand this, but it seems like the compiler wants to know what class the callback functions are going to come from. I can see why it might need that. So I kind of blindly follow the pattern the compiler gives me, and change my struct to:
struct dispatchItem {
let description: String
let f: (MasterDispatchController)->()->Void
init(description: String, f: @escaping (MasterDispatchController)->()->()) {
self.description = description
self.f = f
}
}
Great the compiler is happy there, but now when I try to call the function with dispatchItems[indexPath.row].f()
it says:
Missing parameter #1 in call
The function has no parameters, so I got confused...
I thought maybe it was asking me for the instance of the object in question which would make some sense... that would be "self" in my example, so I tried dispatchItems[indexPath.row].f(self)
but then I got an error:
Expression resolves to an unused function
So I'm kind of stuck.
Sorry if this is a stupid question. Thanks for your help.