Updated 2 December 2021
In this blog, we will know about control flow in swift
There are multiple types of control flow in swift:-
While loop will perform on a single condition. It will perform until the condition will false.
1 |
while condition {statements} |
the flow of the while loop:-
1. It will check the condition
2. if it is true
3. then it will execute the statement
4. if it is false
5. then it will not execute the statement
for example
1 2 3 4 5 6 |
let number = 10 while number > 0{ print(number) number = number + 1 } |
In this loop we can perform the statement until the condition
Syntex:
1 2 3 |
for val in sequence{ // statements } |
example:-
1 2 3 |
for val in 1..<10{ print(val) } |
the flow of the for in loop:-
1. it will check the condition
2. if it is true
3. then it will execute the statement
4. it will increase the value of val
5. if it is false
6. then it will not execute the statement
it will compare the two objects and on the result of the comparison it will perform the statement
Syntex:-
1 2 3 4 5 |
if obj1 == obj2{ }else{ } |
example:-
1 2 3 4 5 6 7 8 9 |
var num1 = 1 var num2 = 2 if num1 == num2 { print("true") }else{ print("false") } |
It works the same as if-else it will check the condition and perform accordingly
Syntex:-
1 2 3 |
guard let obj1 = obj2 else { return } |
example:-
1 2 3 4 5 6 7 |
var obj1: String = "" guard let obj2 = obj1 else { return } |
if obj1 has nil value then it will perform return and if it has value then it will assign value in obj2
It will perform like if-else but it is different from the if-else
in switch it will check the each condition and if it is matched to any one it will stop the matching with other
it has a default statement if there is not any matched statement then it will perform default statement
Syntex:-
1 2 3 4 |
switch obj{ case: defaults: } |
for example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
func checkswitch(num:Int){ switch number { case 1: print("1") case 2: print("2") case 3: print("3") defaults: print("defaults") } } |
call the function checkswitch with the integer parameter
I hope this blog will help you to understand Swift control flow if you have any comments, questions, or recommendations, feel free to post them in the comment section below!
For other technical blogs, please click here.
If you want to know more about swift please check here
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.