I am trying to click a button and have it print out the next element in an array. I only want it to show the next element each time you press the button.

var array = ["one", "two", "three"]

@IBAction func Button(_ sender: Any) {
     print(array[1])    
}

2 Answers

0
Jack Bashford On Best Solutions

Make a counter and use modulo:

var array = ["one", "two", "three"]
var counter = 0

@IBAction func Button(_ sender: Any) {
     print(array[counter % array.count])
     counter += 1
}
0
vacawama On

Another way you can get the next item from an array it to make an Iterator. This is useful if you want an exhaustible supply of values.

For example:

var array = ["one", "two", "three"]
var iterator = array.makeIterator()

if let value = iterator.next() {
    print(value)
}
one
if let value = iterator.next() {
    print(value)
}
two
if let value = iterator.next() {
    print(value)
}
three

Once the Iterator is out of values, it returns nil:

if let value = iterator.next() {
    print(value)
} else {
    print("out of values")
}
out of values

You can also use an Iterator in a for-in loop:

var array = ["one", "two", "three"]
var iterator = array.makeIterator()

for value in iterator {
    print(value)
}
one
two
three

You can convert the remaining items into an Array:

var array = ["one", "two", "three"]

var iterator = array.makeIterator()
let first = iterator.next()!

let rest = Array(iterator)
print(first)
print(rest)
one
["two", "three"]