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 a  2s  . c  om
   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])/* w w w. j  a va  2  s .  com*/
}

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