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 trialMateo Sossah
6,598 PointsHow to use showFunFact to display the quotes from the factsArray in the index order?
I'd like to not have the quote picked randomly, but displayed in the order of Index. viewDidLoad = 0 first click = 1 second click = 2 ...etc
If anyone could help me with that it would be awesome!!!
2 Answers
Damien Watson
27,419 PointsHi, I'm not quite up on swift as objc, but you are on the right path. Set a variable to track the current Fact (starting at 0), then increment it. When greater than or equal to the array amount, set back to 0.
This is how I achieved it in swift (note: I am accessing the factsArray directly):
class ViewController: UIViewController {
@IBOutlet weak var funFactLabel: UILabel!
@IBOutlet weak var funFactButton: UIButton!
var factBook = FactBook()
let colourWheel = ColourWheel()
// Define the fact pointer
var currentFact = 0
override func viewDidLoad() {
super.viewDidLoad()
// Set the fact
funFactLabel.text = factBook.factsArray[currentFact]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func showFactButton() {
// Loop the fact pointer
if ++currentFact >= factBook.factsArray.count {
currentFact = 0
}
// Set the fact
funFactLabel.text = factBook.factsArray[currentFact]
let randomColour = colourWheel.randomColour()
view.backgroundColor = randomColour
funFactButton.tintColor = randomColour
}
}
Mateo Sossah
6,598 PointsThanks Damien!
Damien Watson
27,419 PointsNo Probs.
Mateo Sossah
6,598 PointsMateo Sossah
6,598 PointsThanks!
Here is what I got with swift, starting from your answer, but I get an error message about the "if var" statement = "variable binding in a condition requires an initializer". Do you know what's the issue?
import UIKit
class ViewController: UIViewController {
// funFactLabel.text = factBook.randomFact() funFactLabel.text = factBook.factsArray[arrayIndex] }
}
Damien Watson
27,419 PointsDamien Watson
27,419 PointsHi Mateo,
Looks like the lines are a bit mashed up, I have taken your 'showFunFact' method and cleaned it up below. You had the 'var' in the if statement it is already assigned, so you don't need this. Also you had an 'else' which is not required as the arrayIndex gets set back to 0 (first item), it will just continue to loop.