Swift For-in Loop

In swift, for-in loop is used to iterate over a sequence of items, such as items in an array list, characters in string or collection of items to execute specified statements repeatedly based on the defined conditions.

 

If we get requirements like need to execute set of statements repeatedly based on the items in list or array then by using for-in loop we can easily achieve this functionality in swift programming language.

 

Now we will see the functionality of for-in loop in swift programming language using algorithm diagram.

Swift For-In Loop Flow Diagram

Following is the swift for-in loop statement flow diagram to represent how the functionality of for-in loop will work in a swift programming language.

 

Swift for in Loop Flowchart Diagram with Examples

If you observe above swift for-in loop flow diagram it will loop through the list till it reach the end of the items in a defined list.

Syntax of Swift For-In Loop

Following is the syntax of defining for-in loop in swift programming language.

 

for item_name in list_name {

// your statements

}

If you observe above swift for-in loop syntax we defined multiple parameters those are

 

Item_name – By using this we can access each item in defined list.

 

list_name – Its name of the list which we need to access the items.

 

Now we will see how to use a for-in loop in a swift programming language with examples.

Swift For-In Loop Example

Following is the simple example using for-in loop in swift to loop through the list of items.

 

var lstNames: [String] = ["Suresh","Khawar"]

 

for index in lstNames {

print( "Name of Developer is \(index)")

}

If you observe the above for-in loop example we are looping through the items in “lstNames” array list to print each item in the list.

 

When we execute the above program in swift playground we will get a result like as shown below.

 

Name of Developer Suresh

Name of Developer Khawar

This is how we can use for-in loop in swift programming language to loop through the sequence of items in list based on our requirements.