Introduction to Swift: Control Statement

Codes typically flow from the top to bottom. With the implementation of control flow, it will break the flow by the execution of decision making. That decision making could be implemented either using:

  • while loop to perform a task multiple times
  • if and switch statement to execute different part of the code based on certain conditions.
  • for-in loop to go through either the arrays, dictionaries, ranges, strings or other sequences. (Notice the plural ‘s’)

For-in loop

With this loop functionality, it is mostly used to retrieve information. By looking at the code below, we have an array that contains an information and we needed to extract that information out. We simply do that by using for-in loop by storing each of the information of the array in a new variable called fruit. And the rest is self-explanatory.

If conditional statement

This statement is one the most widely used in the world of coding as it helps identify conditions met and then execute the commands. With the implementation of if statement, in most cases, you have to include else in it. I’ll show you an example of this. Here we have a variable of age containing 15 and we would like to buy a movie ticket. Here we can see that if the age is below 6, the movie ticket will then be $2 and everything else would be $5.

Switch conditional statement

This statement has the same functionality as if conditional statement. Instead of using if here, we are using case to determine the conditions. Here we implemented the same code as above except it is written differently. When it comes to implementing more conditions, switch is always better to use as compared to if conditional statement.

While loop

While loop typically start by evaluating a single condition either true or false. If the condition is true, then it will execute the statement until it becomes false. To get an idea of how this actually work, simply launch it on your XCode. You will notice the code will continue to print it out infinitely.

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*