目前我正在传递一个闭包作为对象的属性,该对象不接受任何参数并且没有返回值,如下所示:
class MyClass {
var myClosureProperty: (() -> ())? {
didSet {
doSomeActionWhenClosureIsSet()
}
}
}
var instanceOfMyClass = MyClass()
instanceOfMyClass.myClosureProperty = {
// do some things here...
}
到目前为止,这一切都很好。我希望在设置要在 MyClass 实例中使用的闭包时能够传入一个参数。我正在寻找类似下面的内容,尽管我确定语法不正确:
class MyClass {
var myClosureProperty: ((newString: String) -> ())? {
didSet {
doSomeActionWhenClosureIsSet(newString)
}
}
func doSomeActionWhenClosureIsSet(stringParam: String) -> () {
// create a button with the stringParam title...
}
}
var instanceOfMyClass = MyClass()
instanceOfMyClass.myClosureProperty = {("Action")
exampleFunction()
}
我将如何向这个闭包传递一个可以在 MyClass 内部使用的参数 - 即一个可以在属性本身的 didSet 部分内部使用的值,如第二个示例所示?
编辑:这是最终对我有用的东西:
class MyClass {
var myClosurePropertyWithStringAndAction: (buttonName: String, closure: (() -> ()))? {
didSet {
let buttonTitle = myClosurePropertyWithStringAndAction!.buttonName
createButtonWithButtonTitle(buttonTitle)
}
}
func createButtonWithButtonTitle(buttonTitle: String) -> () {
// here I create a button with the buttonTitle as the title and set
// handleButtonPressed as the action on the button
}
func handleButtonPressed() {
self.myClosurePropertyWithStringAndAction?.closure()
}
}
}
下面是我在实例上调用它的方式:
instaceOfMyClass.myClosurePropertyWithStringAndAction = ("Done", {
// do whatever I need to here
})
最佳答案
由于您正在尝试设置 pass 2 东西,一个闭包和一个按钮名称,您将无法使用闭包的简单 setter 来完成此操作。
您的限制是这两件事相互依赖,因此您必须同时设置或都不设置。
首先,将 newString
添加到您的闭包中并没有按照您的想法进行。它是一个参数,因此您可以在调用它时将字符串传递给闭包,它不是在定义闭包时传递字符串的方法。
做你想做的事情的“快速方式”可能是将它定义为一个元组。您可以命名元组中的值,这样它就可以按照您想要的方式工作。像这样尝试:
class MyClass {
var stringAndClosure: (buttonName: String,closure: (() -> ()))? {
didSet {
//create button named buttonName
let name = stringAndClosure!.buttonName
}
}
}
let instanceOfMyClass = MyClass()
instanceOfMyClass.stringAndClosure = ("Action",{ exampleFunction() })
关于ios - 带参数的 Swift 传递闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24207986/