I've been trying to create a menu item for my application in swift, and by pressing different buttons on the menu I want to run different python scripts. I'm very new to Swift, and I'm guessing there's a simple mechanic I'm just missing here.
The problem is now that I'm trying to create a button, with an action being run when it is pressed.
The function call is in a Toolbar, which is in itself in a NavigationView:
ToolbarItem {
Menu {
Button("Label", action: myFunc("My string"))
} label: {
Label("Scripts", systemImage: "applescript")
}
}
Where the function myFunc is like this:
func myFunc(_ param: String) -> Void {
print(param)
}
(The integer is just a placeholder for a later value which would correspond to the path of the script I'm trying to run)
The error is:
Cannot convert value of type 'Void' to expected argument type '() -> Void'
The weird thing is that when I exclude the argument in the function call, like calling a:
func myFunc() {
print("Hello")
}
From the same location, it works just fine. Is there a limitation to the buttons like not being able to send arguments to their functions?
I've looked at different solutions, but they all seem way too complicated for this error. I saw one guide where it was because of an empty view, but this doesn't seem to be the error at hand.
The amount of buttons will later be in a ForEach. I'm however a bit conflicted regarding what the best way of storing the paths for the scripts is. I've been thinking about doing an enum with the different paths as rawValues. But I'd like different labels for the buttons than the actual paths of the files, so I'd need two values stored in the rawValues, is this possible? Like using a dictionary and using the name as key and the value as the path. Or do you have any inputs on a better way to solve this problem?
I'm very open for suggestions, the goal is just to be able to run scripts with buttons in a menu!
question from:
https://stackoverflow.com/questions/65920732/unable-to-run-function-with-arguments-in-swift 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…