Swift 中块的语法 [英] Syntax of Block in Swift

查看:16
本文介绍了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)
})

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

for more info about closures see the chapter in the swift docs

关于 CGRect() 的注意事项 - developer docs 显示 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 中块的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆