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 trialGary Adams
Courses Plus Student 1,176 PointsiOS 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
7,810 PointsTry 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
7,810 PointsYou 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.
Gary Adams
Courses Plus Student 1,176 PointsThanks for your response! Does this look right?
@IBAction func showFunFact() { funFactLabel.text = factBook.factsArray[0++] }
Andres Oliva
7,810 PointsNope, that won't work.
Try using a variable instead of putting a zero there.
Gary Adams
Courses Plus Student 1,176 PointsWell... I'm not getting far.
var count = thisArray.count
thisArray[0...count]
Gary Adams
Courses Plus Student 1,176 PointsYou'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
7,810 PointsThat's weird. But glad I could help!
Goran Jakovljevic
920 PointsHere is my code:
var i = 0
@IBAction func ButtonPressed() {
funFactLabel.text = factBook.factsArray[i]
i++
if i == (factBook.factsArray.count) {
i = 0
}
}
Andres Oliva
7,810 PointsAndres Oliva
7,810 PointsHey, 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 :)