swift中带有可选闭包的参数

Ren*_*ers 6 parameters closures optional swift

我正在使用可选的闭包,但无法找到传递参数的方法.到处搜索,尝试了所有的建议,但无法让它工作.

我的代码:

func DoAlert(title: String
    , message: String
    , actions: String
    , sender: AnyObject?
    , Ctlr : UIViewController
    , SegueString: String?
    , YesClosure: ()->() = {}
    , NoClosure: ()->() = {}
    , StartClosure: ()->() = {}
    , EndClosure: ()->() = {}
    ) {

if (actions.rangeOfString("Ok") != nil {
        alert.addAction(UIAlertAction(title: "OK", style: .Default ) { action -> Void in
            EndClosure()
            })}
} // end function
Run Code Online (Sandbox Code Playgroud)

我想为Ok添加一个闭包,其中需要'self'参数.

如下所示:

    // add to func doAlert: 
    , OkClosure: (AnyObject)->() = {}


            // add to action Ok (before the EndClosure: 
            OkClosure(sender!)
Run Code Online (Sandbox Code Playgroud)

在第一行获取错误:AnyObject不是()的子类型

如果我将AnyObject从第一行中删除,则获取错误:无法将表达式的类型'AnyObject'转换为'()=>()'

所有其他试验给我类似的'元组'错误.如何在代码中的可选闭包中编写参数传递的代码?

ABa*_*ith 18

首先,要使用闭包作为函数的参数,您应该像这样声明它们:

func myFunc(closure: (Int) -> Void) {
    // Now I can call closure like so:
    let myInt = 10
    closure(myInt)
}
Run Code Online (Sandbox Code Playgroud)

(正如@Airspeed Velocity所指出的那样,周围的括号Int并不是严格要求的,因为只有一个参数.你是否包含它们只是个人偏好)

其次,您可以修改前一个函数以包含一个可选的闭包,如下所示:(注意?闭包周围的括号和括号表示闭包是可选的,而不是返回类型)

func myFunc(closure: ((Int) -> Void)?) {
    // Now when calling the closure you need to make sure it's not nil.
    // For example:
    closure?(10)
}
Run Code Online (Sandbox Code Playgroud)

第三,要添加一个默认值nil,这就是你试图用它做= {}的结果YesClosure: ()->() = {},你可以这样做:

func myFunc(closure: ((Int) -> Void)? = nil) {
    // Still need to make sure it's not nil.
    if let c = closure {
        c(10)
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,就像注释一样,您可以设置闭包的参数名称,这样可以更容易地识别在调用它时传递给闭包的内容.例如:

(注意 - 这里需要括号括起来value: Int)

func myFunc(closure: ((value: Int) -> Void)) {
    closure(value: 10)
}
Run Code Online (Sandbox Code Playgroud)

最后,你可以使用typealias.根据文件:

类型别名声明将现有类型的命名别名引入程序.

以下是如何将其与闭包一起使用的示例:

typealias MyClosureType = () -> Void

func myFunc(closure: MyClosureType) {
    closure()
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!