Home > Blockchain >  How do I loop back to the first item in an Array?
How do I loop back to the first item in an Array?

Time:12-30

I'm sure this is very simple, but I'm using a button to go to the next item in an array and display it in a label. That much works just fine, however once the end of the array is reached the app crashes since there are no items left to display. How do I get it to go back to the first item? I've tried an If statement but had no luck.

import UIKit

class ViewController: UIViewController {

var firstQuote = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBOutlet weak var quotesLabel: UILabel!

var quotes = ["","Quote 1", "Quote 2", "Quote 3"]

@IBAction func nextButton(_ sender: UIButton) {    

firstQuote = firstQuote   1
quotesLabel.text = quotes[firstQuote]     
    
}
}

This is the If Statement I tried

@IBAction func nextButton(_ sender: UIButton) {
    

    
    if firstQuote < quotes.count{
    firstQuote = firstQuote   1
    quotesLabel.text = quotes[firstQuote]
}

    if firstQuote == quotes.count{
    firstQuote = 0
    quotesLabel.text = quotes[firstQuote]
    }  
}

CodePudding user response:

A common solution is to use % (the remainder operator) to wrap firstQuote back to 0 when it is equal to quotes.count:

firstQuote = (firstQuote   1) % quotes.count

CodePudding user response:

This works for me

  • Related