get the next item in a list (if last item, cycle back to get first item) in swift

You can use the following code snippet to get the next item in a list and cycle back to the first item if it is the last item:

main.swift
var currentIndex = 0
let myList = ["item1", "item2", "item3"]

func getNextItem() -> String {
    let currentItem = myList[currentIndex]
    currentIndex = (currentIndex + 1) % myList.count
    return currentItem
}
215 chars
9 lines

In this example, we first define a variable currentIndex to keep track of the current item in the list. We also define a list called myList which contains the items.

The getNextItem() function returns the current item in the list (currentItem) and then increments the currentIndex. The currentIndex is then used to access the next item in the list. If the currentIndex is equal to the length of the list, it is reset to 0 using the modulo operator %.

This ensures that the function will cycle through the list and return the first item again after the last item has been returned.

related categories

gistlibby LogSnag