Everything works well except on the last element of the array, I get fatal error: Array index out of range when I click on SnapButton. I tried to add:
//var indexA = getRandomIntFromArray(cardNamesArray)
//var indexB = getRandomIntFromArray(cardNamesArray2)
but I get cannot be used on type View Controller not sure what this means
var firstRandomNumber = Int()
var secondRandomNumber = Int()
class ViewController: UIViewController {
@IBOutlet weak var FirstCardImageView: UIImageView!
@IBOutlet weak var SecondCardImageView: UIImageView!
@IBOutlet weak var PlayRoundButton: UIButton!
@IBOutlet weak var BackgroundImageView: UIImageView!
@IBOutlet weak var playerScoreLabel: UILabel!
var playerScore: Int = 0
var cardNamesArray = ["acorn", "angry","apple", "rainbow", "sad","boots", "heart", "pumpkin","chestnuts"]
var cardNamesArray2 = ["bellota", "enfadado","manzana", "arcoiris","triste","botas","corazon", "calabaza", "castana"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playRoundTapped(sender: UIButton) {
firstRandomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(cardNamesArray.count)
FirstCardImageView.image = UIImage(named: cardNamesArray[firstRandomNumber])
secondRandomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(cardNamesArray2.count)
SecondCardImageView.image = UIImage(named: cardNamesArray2[secondRandomNumber])
}
func getRandomIntFromArray(array: [String]) -> Int {
return GKRandomSource.sharedRandom().nextIntWithUpperBound(cardNamesArray.count)
}
//var indexA = getRandomIntFromArray(cardNamesArray)
//var indexB = getRandomIntFromArray(cardNamesArray2)
@IBAction func SnapButtonTapped(sender: UIButton) {
if cardNamesArray.count > 0 {
if firstRandomNumber == secondRandomNumber {
cardNamesArray.removeAtIndex(firstRandomNumber)
cardNamesArray2.removeAtIndex(secondRandomNumber)
firstRandomNumber = getRandomIntFromArray(cardNamesArray)
secondRandomNumber = getRandomIntFromArray(cardNamesArray2)
//on the last element of the array when I click on SnapButtonTapped I get fatal error: Array index out of range
FirstCardImageView.image = UIImage(named: cardNamesArray[firstRandomNumber])
SecondCardImageView.image = UIImage(named: cardNamesArray2[secondRandomNumber])
print(cardNamesArray)
} else {
print("no cards in array")
}
}
}
}