Swift - Iterating over an Array

Introduction

To iterate over an array, you can use the For-In loop, like this:

Demo

var OSes = ["iOS", "Android", "Windows Phone"]
for OS in OSes {//ww w . j  a v a2  s.  c  o  m
   print(OS)
}

Result

You can also access specific elements in the array using its indices:

Demo

var OSes = ["iOS", "Android", "Windows Phone"]
for index in 0...2 {
     print(OSes[index])/*  www .  ja v a 2s  .c om*/
}

Result

If you need the index and value of each element in the array, use the global enumerate function to return a tuple for each element in the array:

Demo

var OSes = ["iOS", "Android", "Windows Phone"]
for (index, value) in enumerate(OSes) {
     print("element \(index) - \(value)")
}

Related Topic