Swift 从';调用函数;文本';迅速地

Swift 从';调用函数;文本';迅速地,swift,alert,generics,Swift,Alert,Generics,我正在编写一些通用代码,以便所有视图控制器都可以使用它。 我喜欢使其成为通用的功能之一是警报函数。 这里的问题是,我必须在回复中对操作进行编码。 警告(仅按OK)或一般响应(取消、否)都可以,但当(一般)函数需要运行时,我需要使用技巧来传递哪个函数。 如果我可以从一些文本中运行函数,它将减少问题(并且我不必硬编码所有可以调用的函数)。 还是有更好的方法实现我的“通用”警报 此处示例: func DoAlert(title: String, message: String, actions: St

我正在编写一些通用代码,以便所有视图控制器都可以使用它。 我喜欢使其成为通用的功能之一是警报函数。 这里的问题是,我必须在回复中对操作进行编码。 警告(仅按OK)或一般响应(取消、否)都可以,但当(一般)函数需要运行时,我需要使用技巧来传递哪个函数。 如果我可以从一些文本中运行函数,它将减少问题(并且我不必硬编码所有可以调用的函数)。 还是有更好的方法实现我的“通用”警报

此处示例:

func DoAlert(title: String, message: String, actions: String, sender: AnyObject, viewController : UIViewController) {.......
.....
if (actions as NSString).containsString("Yes") {
    alert.addAction(UIAlertAction(title: "Yes", style: .Default) { action -> Void in
    if (actions as NSString).containsString("Yes'DoAfunction()'") {
        DoAfunction() }
    })} 
.....
}
//我喜欢在“”之间抽象函数,并使用它调用函数,而不是硬编码

//我按如下方式调用该函数:

DoAlert("Warning", alertText, "Yes'DoAfunction()'No", sender, self)
    DoAlert("Warning", alertText, "YesNo", sender, self, YesClosure: DoYesFunction, NoClosure: DoNoFunction)
///////////解决方案:////////////////

根据Bluehound关于使用闭包的建议,我最终为不同的响应添加了可选闭包

对于那些希望这样做的人,以下是我的解决方案:

此处的解决方案:

func DoAlert(title: String, message: String, actions: String, sender: AnyObject, viewController : UIViewController, YesClosure: ()->() = {}, NoClosure: ()->() = {}) {.......
.....
if (actions as NSString).containsString("Yes") {
    alert.addAction(UIAlertAction(title: "Yes", style: .Default) { action -> Void in

    YesClosure()   // This will the run the function if provided

    })} 
.....
}
//我按如下方式调用该函数:

DoAlert("Warning", alertText, "Yes'DoAfunction()'No", sender, self)
    DoAlert("Warning", alertText, "YesNo", sender, self, YesClosure: DoYesFunction, NoClosure: DoNoFunction)
如果要执行nu功能,请将该选项忽略。(以下仅具有“否”功能)


您可以将闭包作为参数传递,而不是传递要完成的函数名。在调用函数时,您可以定义传入函数的内容。例如:

func foo(closure: () -> Void) {
    closure()
}

foo {
    println("Some text")
} // prints Some Text
现在,对于使用多个操作,您可以传递一组闭包,如下所示:

func foo(closures: [() -> Void]) {
    for closure in closures {
        closure()
    }
}

foo([{println("a")},
    {println("b")},
    {println("c")}]) // prints a b c

您可以将闭包作为参数传递,并在闭包调用函数中我对Swift很陌生,所以您可以解释一下,或者让sample?Bluehound,您将我引向了正确的方向。虽然最初不太清楚,但在StackOverflow中找到了使用可选闭包的好示例。我已经为那些感兴趣的人在原始问题区域添加了我的解决方案。