简体   繁体   中英

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 eg

 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: (() -> ())?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM