For Loops in Swift

What is the Swifty way of doing this?

Steven Curtis
The Startup

--

For loops are a basic set of building blocks for programming. But there are Swifty ways to do this; what are they?

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • None, a basic knowledge of programming in Swift would be helpful
  • If you are unsure about odd and even numbers you might read THIS

Terminology

loop: A sequence of instructions repeated until a condition is reached

range: The elements between the highest and lowest values

An example array

In Swift we set up an array arr with 4 elements (a, b, c, and d)

and logically this looks like the following

Looping through an array

Perhaps you want to read each of these elements out in turn.

We are going to use a for loop to do this, and in Swift it is just that we write out each element using print:

--

--