0

Scenario

Let's say I've an array = ["a", "b", "c", "d"]

I have a button function that allows me to print data in this array. I used a for loop to loop through the array.

But after the last array element(which is index[3]) is printed on the fourth click, I want it to print from the start(which is index[0]) on the fifth click.

Any help is much appreciated!

Thank you

1
  • irrelevant question title Commented Apr 24, 2017 at 16:42

5 Answers 5

3

For that you need to simply maintain the index of the current element for array object.

var currentIndex = 0

@IBAction func buttonClick(_ sender: UIButton) {
    print(array[currentIndex])
    currentIndex += 1
    if currentIndex == array.count { 
        currentIndex = 0 
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This should be a comment.
@VishalSonawane Edited answer.
@VishalSonawane :)
3

Keep a click count var (initialize with 0) and use the following when the button is tapped:

let valToPrint = yourArray[clickCount % yourArray.count]
clickCount += 1

print("Current value = \(valToPrint)")

The % (modulos) operator will cycle clickCount through the required range.

3 Comments

If i initialise the var clickCount to 0, the value will not change at all. How should I initialise it?
@Meebfel If clickCount is declared as var then you can of course change it. Maybe you are declaring it inside the function. If so then move it outside of the function.
@Adeel he was right. if clickCount will be initialized to zero then the modulos operator will always reset it to zero due to the operator result. Edited the answer to work properly now.
1

You can write

let letters =  ["a", "b", "c", "d"]
var index = 0

func printNext() {
    print(letters[index])
    index = (index + 1) % letters.count
}

enter image description here

1 Comment

ah yes of course, I skimmed over it too quick, believing you used the index remainder directly!
0

write below code on button click

@IBAction func myButton(_ sender: UIButton) {

    if sender.tag > array.count{
        sender.tag = 0
    }

    print("array[\(sender.tag)] = \(array[sender.tag])")
    sender.tag += 1

}

Comments

0

For the technical joy of it: another alternative would be to define a sequence which cycles over the elements of the array.

Given an immutable array:

class Foo {
    private let array: [String]

    private lazy var cyclingSequenceOverArray: 
        UnfoldSequence<String, Int> = sequence(state: -1) {
        (state: inout Int) -> String? in
        guard !self.array.isEmpty else { return nil }
        return self.array[(state = (state + 1) % self.array.count, state).1]
    }

    init(_ array: [String]) {
        self.array = array
    }

    func printNext() {
        if let next = cyclingSequenceOverArray.next() {
            print(next)
        }
    }
}

let foo = Foo(["a", "b", "c", "d"])

foo.printNext() // a
foo.printNext() // b
foo.printNext() // c
foo.printNext() // d
foo.printNext() // a
foo.printNext() // b

In the case where you let the array be mutable (var) and it ever becomes empty: a call to the next() method (as implemented above) of the sequence will terminate the sequence. I.e., even if the array were to be re-filled, subsequent calls to next() would still yield nil. In this case, you could let the sequence be infinite (never-terminating), simply returning a default value in case the array is nil:

class Foo {
    var array: [String]

    private lazy var cyclingSequenceOverArray: 
        UnfoldSequence<String, Int> = sequence(state: -1) {
        (state: inout Int) -> String in
        guard !self.array.isEmpty else { return (state = -1, "Empty!").1 }
        return self.array[(state = (state + 1) % self.array.count, state).1]
    }

    init(_ array: [String]) {
        self.array = array
    }

    func printNext() {
        if let next = cyclingSequenceOverArray.next() {
            print(next)
        }
    }
}

Example usage:

let foo = Foo(["a", "b", "c", "d"])

foo.printNext() // a
foo.printNext() // b
foo.printNext() // c

foo.array = []

foo.printNext() // Empty!
foo.printNext() // Empty!

foo.array = ["a", "b", "c", "d"]

foo.printNext() // a
foo.printNext() // b
foo.array[2] = "C"
foo.printNext() // C

foo.array = ["1", "2", "3"]

foo.printNext() // 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.