Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

iOS Arrays - What if...

What if you wanted to show the 'fun facts' in order?

The tutorial displays random fun facts and I can't figure out how to display them sequentially.

@IBAction func showFunFact() { funFactLabel.text = factBook.factsArray[9] }

6 Answers

Andres Oliva
Andres Oliva
7,810 Points

Try something like this:

var index = 0

@IBAction func showFunFact() {
 funFactLabel.text = factBook.factsArray[index]
index++
if (index > factBook.factsArray.count - 1) index = 0
 }

You could increment the index like this too:

 funFactLabel.text = factBook.factsArray[index++]

But then you'd begin displaying the second fact in your array.

Andres Oliva
Andres Oliva
7,810 Points

Hey, I just realized that you can increment the index the other way as well and it would be the same, as the variable gets incremented after it is used :)

Andres Oliva
Andres Oliva
7,810 Points

You can simply declare an index property and increment it by one every time you retrieve a fact. Just remember to reset the value to 0 everytime you reach the end of the array of facts.

Thanks for your response! Does this look right?

@IBAction func showFunFact() { funFactLabel.text = factBook.factsArray[0++] }

Andres Oliva
Andres Oliva
7,810 Points

Nope, that won't work.

Try using a variable instead of putting a zero there.

Well... I'm not getting far.

var count = thisArray.count

thisArray[0...count]

You're awesome. Thanks for helping me understand that array property!

... xcode expected curly brackets after the "if"

 @IBAction func showFunFact() {
        funFactLabel.text = factBook.factsArray[index]
        index++
        if (index > factBook.factsArray.count - 1) {index = 0}
    }
Andres Oliva
Andres Oliva
7,810 Points

That's weird. But glad I could help!

Here is my code:

    var i = 0
    @IBAction func ButtonPressed() {
        funFactLabel.text = factBook.factsArray[i]
        i++
        if i == (factBook.factsArray.count) {
            i = 0
        }
    }