In Swift Language Tutorial for Beginner 2 - Data Type, we learned about Swift’s data type, and this time we’ll take a look at the control statements in Swift.
Similar to other high-level languages, Swift also consists of three main control statements, namely: order, branching (conditional), and looping.
Unlike C/C++ or Java, Swift has no entry functions, in this regard it is more like dynamic languages such as Python, Basic, etc. So the swift version of the classic Hello World becomes the following form:
1 | print("Hello, World") |
For the print function, swift also lets us output variables with placeholders, rewriting the Hello World routine above:
1 | var name = "World" |
Branch - If statement
In swift, the main branch statement is also the if statement that we are familiar with. Just in terms of writing, even the parentheses of the wrapping condition expression can be omitted, such as:
1 | var c = 10 |
Of course, there are also if-else combinations, such as:
1 | var c = 10 |
Multi-branching:
1 | if c>0 && c<10 { |
Branch - Switch statement
Of course, multiple branches can also use switch statements, and in switch, unlike C/C++, swift can use more than just integers as conditions, such as:
Use the switch statement for character branching judgment
1 | var charac:Character = "b" |
Multiple branches can be included in the same case, such as:
1 | var charac:Character = "b" |
If it is an order value, you can also use a range in a case, such as:
1 | var num = 3 |
Loop - for statement
In swift, the for statement of the control loop is closer to the syntax of a dynamic language (e.g., Python) than to the syntax of C/C++.
A basic for statement routine is as follows:
1 | for index in 1...5 { |
The statement will print 1,2,3,4,5, Note: It’s three “.”, not two
If you do not need to use index in the loop, you can use the placeholder : _” instead of the variable, which you can write:
1 | var sum=0; |
Of course, the for statement is also convenient for iterating over collection types (Set, Dictionary, Array). We’ll show you this part when we talk about collections.
Loop - repeat-while statement
When you are unsure of the number of loops, you can use repeat-while statements, such as:
1 | var j=0 |
Next
Next, we’ll briefly introduce two special types in Swift - tuples and optionals Swift Language Tutorial for Beginner 4 - Tuple .