If you’re new Swift, an essential programming technique involves iterating through an ordered collection like an Array, Dictionary, or Set. However, unlike Java and Python, recent Swift versions no longer support the typical 3-part for-loop syntax. However, in its place, we have other techniques, including fast enumeration, while loops and the stride iteration syntax. Let’s review how these work!
Swift Fast Enumeration
Fast enumeration is a basic model that provides a quick mechanism to iterate through a collection series:
var numberList: Array<Int> = [8, 2, 10, 7, 5] //fast enumeration for item in numberList { print(item) } //for loop with half-open operator for index in 0..<numberList.endIndex { print(index) numberList[index] } //return tuple combination - index and value for (index, value) in numberList.enumerated() { print("the index \(index) contains value \(value)..") }
A Swift loop can be initialized to zero or defined as a range using a half-open operator. However, what’s missing is being able to control the loop iteration sequence. This technique provides more flexibility - perhaps iterating through the series in reverse. In this case, the built-in reverse function can be applied. As shown, reverse is used to reverse a collection of strings or characters:
//reverse a string var someArray: String = "Swift" var result = String(someArray.reversed()) //reverse a collection var testArray: Array<Int> = [8, 10, 2, 9, 7, 5] var listResult = Array(testArray.reversed())
Swift While Loop
What’s nice about the while-loop is that it’s a widely adopted format present in other languages. If you applied this technique in a technical interview, others would have little problem following your logic. I often use the while loop syntax when building my own data structures or algorithms.
var numberList: Array= [8, 2, 10, 7, 5] var index: Int = 0 //prints 8, 2, 10, 7, 5 while index < numberList.endIndex { print(numberList[index]) index += 1 }
Strideable Protocol
For finer control, the Strideable protocol can be applied. As the name implies, stride can be used to produce specific results. While more verbose, this syntax provides good flexibility. When applied, stride allows one to skip items or iterate through a collection in reverse with a consistent format.
var numberList: Array<Int> = [8, 2, 10, 7, 5] //forward stride enumeration for index in stride(from: 0, through: numberList.endIndex - 1, by: 1) { print(numberList[index]) } //forward stride enumeration - every two for index in stride(from: 0, through: numberList.endIndex - 1, by: 2) { print(numberList[index]) } //reverse stride enumeration for index in stride(from: numberList.endIndex - 1, through: 0, by: -1) { print(numberList[index]) }
Other Study Lists
If you haven’t already, be sure to also review my other lists as they relate to computer science and Swift / iOS development.