Skip to main content

Swift For Loop

The For-in loop are used to iterates arrays, sets, string, dictionary elements and range conditional situation.

//Defining a array of 4 integers
var myArrayElements=[1,2,3,4]

//iterating arrays elements
for item in myArrayElements{
  print("\(item)") //display elements of array
}

Output

1
2
3
4

When we are iterate dictionary elements that is combination of key and value pair. We can get this elements in tuple form (key,values). See this example.

let codeStyle=["A":"Algorithm Code",
        "B":"Byte Code",
        "C":"Compile Code",
        "D":"Documented Code",
        "E":"Error Free Code",
        "F":"Feel Code",
        "G":"Good Code",
        "H":"High Level Code",
        "I":"Incoming Code",
        "J":"Genius Code",
        "K":"Know About Code",
        "L":"Large Code",
        "M":"Move Code",
        "O":"Optional Code",
        "P":"Programming Code",
        "Q":"Quickly Code",
        "R":"Regular code",
        "S":"Short Code",
        "T":"True Code",
        "U":"Your Code",
        "V":"Virus Free Code",
        "W":"Warning free Code",
        "X":"XML Code",
        "Y":"Yahoo Code",
        "Z":"Zebibyte Code"]

//iterate dictionary item
for (my, style) in codeStyle.sorted(by : <){
  print("\(my) : \(style)")
}

Output

A : Algorithm Code
B : Byte Code
C : Compile Code
D : Documented Code
E : Error Free Code
F : Feel Code
G : Good Code
H : High Level Code
I : Incoming Code
J : Genius Code
K : Know About Code
L : Large Code
M : Move Code
O : Optional Code
P : Programming Code
Q : Quickly Code
R : Regular code
S : Short Code
T : True Code
U : Your Code
V : Virus Free Code
W : Warning free Code
X : XML Code
Y : Yahoo Code
Z : Zebibyte Code

That is a way to iterate dictionary items by for loop.

Loops iterate in Numeric range

iterate for loop in numeric range. That is useful when we are know about that exactly how many number of this loop are iterate (execute) statements.

//Range from 10 to 17
for value in 10...17{
  print("\(value)")
}

Output

10
11
12
13
14
15
16
17

In this example for loop are executed 8 times. range are used to define by (closed range operator ...) triple dot operator (F...L). And first (F) element is provide starting range of loop iteration and last (L) element is decide end point of range. If you are understand this point, Then find the output of this program.

//Range from -21 to -17
for value in -21 ... -17{
  print("\(value)")
}

Other example

for i in Swift.stride(from: 0, to: 10, by: 2) {

    print("\(i)")
}

Output

0
2
4
6
8

Use to filter a collection element

let codes = ["C","C++","Java","Python","Swift","C#"]
var result = -1
let findValue = "Swift"
for (index,value) in codes.enumerated(){
    
    if(value==findValue){
       result = 1   
       print("Swift value is founded at index \(index)")
       break
    }
}
if( result == -1){
    
    print("\(findValue) are not exist in given collection")
}

Output

Swift value is founded at index 4
//Array which is containing collection of set
let language = [("C++",1979),
                ("Java",1995),
                ("Swift",2015),
                ("Python",1991),
                ("Smalltalk",1972),
                ("Prolog",1972)]

//Get language which is created 1971 and exist in collection of language
for case let (programming, 1972) in language {
    print("\(programming) are developed in the year 1972")
}

Output

Smalltalk are developed in the year 1972
Prolog are developed in the year 1972

Use continue statement

let mixData : [Any] = [1,true,false,"Swift",10.20]
print("Print all array elements :") 

//Display all array element
for i in mixData {
    print("\(i)",terminator:"  ")
}

print("\nPrint element which is not contain boolean data : ")

for i in mixData {
    if(type(of:i)==Bool.self){
        continue //Continue when find boolean data value
    }
    print("\(i)",terminator:"  ")
}

Output

Print all array elements :
1  true  false  Swift  10.2  
Print element which is not contain boolean data : 
1  Swift  10.2 

Break Statement

let symbol = "+-=*&^%!$#@;?>"
print("Symbol : \(symbol)")

for charAt in symbol{
    
    if(charAt == "!"){
        break
    }
    print(charAt)
}

Output

Symbol : +-=*&^%!$#@;?>
+
-
=
*
&
^
%




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment