Swift中Block的语法 [英] Syntax of Block in Swift
问题描述
我正在尝试从Objective-C重写为Swift,我无法弄清楚语法或理解文档
I am trying to rewrite from Objective-C to Swift, I cannot work out the syntax or understand the docs
这是Objective-C中的简化示例写道:
Here is a simplified example in Objective-C I wrote:
[UIView animateWithDuration:10.0 animations:^{self.navigationController.toolbar.frame = CGRectMake(0,10,0,10);}];
如何在Swift中写这个?
How do I write this in Swift?
这是模板自动完成给出:
This is the template autocomplete gives:
UIView.animateWithDuration(duration: NSTimeInterval, animations: (() -> Void))
推荐答案
由于预期的参数类型和动画参数的返回类型是已知的,编译器可以毫无问题地推断它们。这应该有用(虽然我目前没有可用的游乐场:
Since the expected argument types and return type to the animations argument are known the compiler can infer them without a problem. This should work (though I don't have the playground available right at the moment:
UIView.animateWithDuration(10.0, animations: {
self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
})
有关闭包的更多信息,请参阅 swift docs中的章节
for more info about closures see the chapter in the swift docs
关于 CGRect()
的注释 - 开发人员文档显示 CGRect()
在swift代码中使用。也许它需要导入?
note about CGRect()
- the developer docs show CGRect()
being used in swift code. Perhaps it requires an import?
更新注释:你也可以使用这样的尾随闭包:
update for comments: you can also use a trailing closure like so:
UIView.animateWithDuration(10.0) {
self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
}
这篇关于Swift中Block的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!