Reputation: 3961
I have two basic String Arrays which are being used to display Reptile / Mammal facts.
let reptiles = ["Chameleon", "Snake", "Turtle"]
let mammals = ["Dogs", "Cats", "Bears"]
There are two buttons for each. Mammal button & Reptile button. Users can click each to get a random fact.
func getRandomReptile() -> String {
var randomNumber = Int(arc4random_uniform(UInt32(reptiles.count)))
while previousNumber == randomNumber {
randomNumber = Int(arc4random_uniform(UInt32(reptiles.count)))
}
previousNumber = randomNumber
allArray.append(reptiles[randomNumber])
return reptiles[randomNumber]
}
func getRandomMammal() -> String {
var randomNumber = Int(arc4random_uniform(UInt32(mammals.count)))
while previousNumber == randomNumber {
randomNumber = Int(arc4random_uniform(UInt32(mammals.count)))
}
previousNumber = randomNumber
allArray.append(mammals[randomNumber])
return mammals[randomNumber]
}
What is the best way for a "Go Back" button to display the previous fact? It can be either a Reptile or Mammal fact, depending on what the user pressed.
I approached this by storing each of the Animals in an allArray Array using the append method. Then just using the removeLast method. This doesn't work cleanly, though, as the "back" button requires two taps. (one to remove, the other to display.) - I also don't think it's a very clean approach.
func getPrevious() -> String {
if allArray.count > 1 {
allArray.removeLast()
return allArray.last!
}
else {
return allArray.last!
}
}
What is the cleanest approach to "Go Back" on a combination of two random arrays?
Upvotes: 0
Views: 394
Reputation: 620
save the selections in an array and add every new selection to that array. Walk back the array when you click previous button
Upvotes: 1