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  ava 2 s. 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])//from   w  w  w. j  a v a2  s . c  o m
}

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