A perfect execution of the basics is what the difference is between being good and being great. A for-in loop is basic but the execution, when done correctly, can be something of beauty. The goal here is to try and give you something easy to understand and remember. A core concept that you can and will use with ease and grace on your future projects. We will start with the for-in loop in this article. In the next article we will tackle while and repeat while. After that article we will discuss a forEach loop and how it differs from a for-in loop.
Apple’s documentation describes it like this:
“You use the
in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.”
To start we will focus on the basics then progress to more advanced use cases. For our example we will use an analogy of an actual building. Lets say we want to make a building like the one above. What are the things we would need?
- Building info: “Empire State Building”, “New York”, “48th-tallest in the world”
- The size of the building: “height”: 1250, “widthEastToWest”: 424, “widthNorthToSouth”: 187
- How many windows in building: 6500
- How many floors are in the building: 102
Open a playground titled whatever you would like:
So lets focus on getting the building info:
In this example we use an array to iterate over the items. Adding a word (in this case “info”) after the for keyword turns that word into a constant. That value is automatically set at the start of each iteration loop. The output from this will be:
Empire State Building
48th-tallest in the world
Ok, now lets move on to the building dimensions:
The output is:
height is equal to 1250
widthEastToWest is equal to 424
widthNorthToSouth is equal to 187
Alright. Next is the number of windows:
There are 102 floors within the empire state building and 6500 windows! We wont get crazy exact here as there are other ways of doing this more precisely. But for the sake of simplicity and in lieu of this tutorial we will assume every floor has 64 windows.
In this example we use a range. It iterates 102 times representing the number of floors. The value of windows is set to the first number in the range (1) and the statements inside the loop (the print statement) are executed. This loop will continue to execute through the range until it reaches the end (102). The value of windows is updated to contain the next value and so on until it reaches the end of the range. So the beginning output is:
1 times 64 is 64
the loop iterates through the range and ends with:
102 times 64 is 6528
So there you have it! Easily understood logic that will have a profound impact on how you manage data in the future.