0

我有一个带有以下参数的 CustomAlertView:

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

...通过以下方式调用专用函数:

Button(action: {buttonAction() })

我可以使用以下代码运行代码和任何功能

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

    showCustomAlert = true

...

  func closePopup() { showCustomAlert = false }

我想添加一些带参数的函数,例如

 closePopupAndGetItemWithID(1)

但我不能打电话给他们,它说:

无法将“()”类型的值转换为预期的参数类型“(() -> ())?”

我如何需要在我的 CustomAlertView 中转换 var 以允许有和没有参数的函数?

谁能解释一下这是什么意思:(()->())?

4

1 回答 1

1

你可以创建一个新的闭包来调用带有参数的函数:

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

关于你的第二个问题:

谁能解释一下这是什么意思:(()->())?

它是 Swift 中闭包的类型注释。第一个()是闭包的参数(在这种情况下没有参数)。第二个是返回值——你很可能Void在其他代码库中看到这一点。然后,它被包裹在括号中,将其分组为一个语句,并?使其成为可选的。

补充阅读:

于 2021-06-03T20:55:01.483 回答