Control Flow

For In Loop in Swift

The for-in loop iterates through every element in a collection (array, set, or dictionary) without specifying size. It behaves like a for each in other languages.

The C-style for loop is now deprecated in Swift. To emulate the C-style for loop, use a range as the collection.

//temporary iterator implicitly declared in the loop
for iteratorVariable in collectionName {
    //the individual element is held in the iterator variable
    //to access the value, just use iteratorVariable

//C-style for loop behavior, start...finish provides the range and increments the iterator by 1
for iteratorVariable in start...finish {



For a dictionary, the two iterator variables are provided in brackets, separated by comma (key, value).

var studentGrades: [Integer] = [50, 89, 75]; 

for grade in studentGrades { 
    print "Grade: \(grade)"
} //prints each value of the array studentGrades (each loop is an element of studentGrades assigned to grade variable)

< Switch Case   |   While Loop >

© 2019 SyntaxDB. All Rights Reserved.