Search code examples
arraysswiftfor-loopindexingwhile-loop

How to to loop through portion of Array in Swift


I want to loop through a portion of an Array in Swift, not the entire array based on the index. The array is coming from an API so I don't know the number of elements in advance.

For example for the array ["Joe's pizza","Sal's Pizza","Pizza Hut"], I would only like to loop through up to the first three (if there three) and then stop. In some cases, the starting array will have less than 3 elements and in other cases more then 3 depending on what the API returns.

My code as follows does not work.

let myArray = ["Joe's","Sal's","Pizza Hut","Domino's","John's","Pizza King"]//from API. Could be more or less
let numElements = myArray.count
if numElements = 0 {
    print("none found")
    return
}
var i = 0
var str = ""
while i <= 2 {
    for i in 1...numElements-1 {
        print(i)
        str = myArray[i]
        print(str)
    }//end for loop
    i+=1
} // end while loop

The code will print the full 6 and not respect the while condition. If I put the while inside the for loop, it will needlessly go through the whole Array which could be quite long even though I only want up to the first 3

How can I limit the range used in the index (when I don't know if the actual array count is less than or greater than the number I'm seeking.

Thanks for any suggestions.


Solution

  • You can use the prefix() method for this since it returns up to the given number of elements from the beginning of the array.

    for element in myArray.prefix(3) {
        print(element)
    }