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 trialronald greti
800 PointsCannot assign to currentIndex in self
I added code to avoid asking the SAME question (random no) twice as follows...
import Foundation
//var currentIndex = 0
struct FactBook {
var currentIndex = 0
//stored propeties...
//------------------------------------------------------------------------------------------------------
let factsArray = [ "Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built."
]
//methods...
//------------------------------------------------------------------------------------------------------
func randomFact() -> String {
var randomIndex: Int
do {
var unsignedArrayCount = UInt32(factsArray.count)
var unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
randomIndex = Int(unsignedRandomNumber)
} while currentIndex == randomIndex
currentIndex = randomIndex
println("the index is \(randomIndex)")
return factsArray[randomIndex]
}
}
However, this does not work, seems the var currentIndex = randomIndex is causing a problem? I have tried adding self. in from but that does not work either? If I place the var currentIndex = 0 outside the struct it works, but then this makes the var global?
ronald greti
800 Pointsronald greti
800 PointsIt turns oh that the function needs to be a 'mutating' function ...
Then you have to instantiate into a variable using a 'var' and not 'let'
var factBook = FactBook()