Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax of Block in Swift

Tags:

ios

swift

swift3

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 wrote:

[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))
like image 746
Ryan Heitner Avatar asked Jun 04 '14 13:06

Ryan Heitner


People also ask

What is block in Swift?

Closures in Swift Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

What is the syntax do in Swift?

Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable ( var ) or constant ( let ). And Swift heavily leverages value types, especially for commonly used types like Arrays and Dictionaries.

What is $0 and $1 in Swift?

$0 and $1 are closure's first and second Shorthand Argument Names (SAN for short) or implicit parameter names, if you like. The shorthand argument names are automatically provided by Swift. The first argument is referenced by $0 , the second argument is referenced by $1 , the third one by $2 , and so on.

What is trailing closure syntax?

A trailing closure is written after the function call's parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don't write the argument label for the closure as part of the function call.


1 Answers

This is the swift closure format:

{(parameter:type, parameter: type, ...) -> returntype in
    //do stuff  
}

This is what you should do:

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

Here is the documentation for closures.

like image 75
67cherries Avatar answered Oct 01 '22 05:10

67cherries