Search code examples
swiftparametersalertview

SwiftUI - CustomAlertView - Run function with parameters on Button press


I have a CustomAlertView with the following parameters:

    public var title: String
    public var buttonText: String
    public var buttonAction: (() -> ())?

... a dedicated function is called via:

Button(action: {buttonAction() })

I can run the code and any functions with the following

   customAlert = CustomAlertView(title: "Item found",
                                      buttonText: "Take it",
                                      buttonAction: closePopup
        )

    showCustomAlert = true

...

  func closePopup() { showCustomAlert = false }

I want to add some functions with parameters e.g.

 closePopupAndGetItemWithID(1)

but I cannot call them, and it states:

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

how do I need to convert the var in my CustomAlertView to allow functions with and without parameters?

can anyone explain what this means: (() -> ())?


Solution

  • You can create a new closure that calls the function with the argument:

    CustomAlertView(
       title: "Item found",
       buttonText: "Take it",
       buttonAction: { closePopupAndGetItemWithID(1) }
    )
    

    Regarding your second question:

    can anyone explain what this means: (() -> ())?

    It's a type annotation for a closure in Swift. The first () is the arguments for the closure (no arguments in this case). The second is the return value -- you're very likely to see this as Void in other codebases. Then, it's wrapped in parenthesis to group it as one statement and the ? makes it an optional.

    Additional reading: