Ryan Heitner Ryan Heitner - 1 year ago 100
Swift Question

Syntax of Block in Swift

I am trying to rewrite from objective C - to Swift, I cannot work out the syntax or understand the docs

Here is a simplified example in Objective C I write

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

How do I write this in Swift - This is the template autocomplete gives

UIView.animateWithDuration(duration: NSTimeInterval, animations: (() -> Void))

Answer Source

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

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download