Swift: For…in function

Another important function in Swift programming is “For”. The goal of this function is to iterate over a range of numbers, characters in a strings or values in an array.

So let’s first use the “for” function in an array.

Screen Shot 2017-04-15 at 13.40.49.png

Basically, we created a variable “pet” that will pick each value from the array “animals” and then we output the value of the variable “pet”. And the function “for” will move from array index to another.

We can also move by 2, so for example, only get the values of the 1st item, then the 3rd, the fifth and so on. To do so, we need to use the “stride” function.

The stride function

Screen Shot 2017-04-15 at 14.33.18.png

So let’s take a look and explain what we just did

Screen Shot 2017-04-15 at 14.07.27.png

So we created a variable “i” that will increase (“stride“) from the value of 0 until it reaches the size of our array animals (animals.count), and we have decided to increment the “i” value by 2 each time.

Another way that we can iterate an array would be to use the 3 points “…” which indicates the beginning and the ending of the iteration. We use “animals.count-1” because an array start at the index 0 (Swift: Arrays). So the number of values in an array will always be higher by 1 with respect to the index of the last value.

Screen Shot 2017-04-15 at 14.31.21.png

 

So you are probably wondering now, how do you decrease the value? Well, we use the “.reversed()” function

The reversed function

Using the reversed function will allow us to output the values from the last to first.

Screen Shot 2017-04-15 at 14.20.53.png

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: