我试图从Objective-C重写为Swift,我无法弄清楚语法或理解文档
这是Objective-C中的一个简化示例我写道:
[UIView animateWithDuration:10.0 animations:^{self.navigationController.toolbar.frame = CGRectMake(0,10,0,10);}];
我如何在Swift中写这个?
这是自动完成模板给出的:
UIView.animateWithDuration(duration: NSTimeInterval, animations: (() -> Void))
67cherries.. 16
这是swift闭包格式:
{(parameter:type, parameter: type, ...) -> returntype in //do stuff }
这是你应该做的:
//The animation closure will take no parameters and return void (nothing). UIView.animateWithDuration(duration: NSTimeInterval, animations: {() -> Void in //Animate anything. })
这是闭包的文档.
这是swift闭包格式:
{(parameter:type, parameter: type, ...) -> returntype in //do stuff }
这是你应该做的:
//The animation closure will take no parameters and return void (nothing). UIView.animateWithDuration(duration: NSTimeInterval, animations: {() -> Void in //Animate anything. })
这是闭包的文档.
由于预期的参数类型和动画参数的返回类型是已知的,因此编译器可以毫无问题地推断它们.这应该工作(虽然我目前没有可用的游乐场:
UIView.animateWithDuration(10.0, animations: { self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0) })
有关闭包的更多信息,请参阅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) }
以下代码可以指导您编写自己的块.
class func testFunc(completion: ((list : NSArray!) -> Void)?) { //--- block code. if completion! != nil { completion! (list: NSArray()) } }
你可以称之为 -
className.testFunc { (list: NSArray!) -> Void in }