Swift中Block的语法

Rya*_*ner 15 ios swift swift3

我试图从Objective-C重写为Swift,我无法弄清楚语法或理解文档

这是Objective-C中的一个简化示例我写道:

[UIView animateWithDuration:10.0 animations:^{self.navigationController.toolbar.frame = CGRectMake(0,10,0,10);}];
Run Code Online (Sandbox Code Playgroud)

我如何在Swift中写这个?

这是自动完成模板给出的:

UIView.animateWithDuration(duration: NSTimeInterval, animations: (() -> Void))
Run Code Online (Sandbox Code Playgroud)

67c*_*ies 16

这是swift闭包格式:

{(parameter:type, parameter: type, ...) -> returntype in
    //do stuff  
}
Run Code Online (Sandbox Code Playgroud)

这是你应该做的:

//The animation closure will take no parameters and return void (nothing).
UIView.animateWithDuration(duration: NSTimeInterval, animations: {() -> Void in
    //Animate anything.
})
Run Code Online (Sandbox Code Playgroud)

这是闭包的文档.


Jia*_*aro 10

由于预期的参数类型和动画参数的返回类型是已知的,因此编译器可以毫无问题地推断它们.这应该工作(虽然我目前没有可用的游乐场:

UIView.animateWithDuration(10.0, animations: {
  self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
})
Run Code Online (Sandbox Code Playgroud)

有关闭包的更多信息,请参阅swift文档中章节

请注意CGRect()- 开发人员文档显示CGRect()在swift代码中使用.也许它需要导入?

更新注释:您还可以使用如下的尾随闭包:

UIView.animateWithDuration(10.0) {
  self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
}
Run Code Online (Sandbox Code Playgroud)

  • @Jiaaro命名参数不是问题.它必须是最后一个论点,就是这样. (2认同)

小智 5

以下代码可以指导您编写自己的块.

class func testFunc(completion: ((list : NSArray!) -> Void)?) {
    //---  block code.
    if completion! != nil {
        completion! (list: NSArray())
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以称之为 -

className.testFunc {
(list: NSArray!) -> Void in
}
Run Code Online (Sandbox Code Playgroud)