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")
}
}
}
}
It appears your array is tracking strings, not images.
This line
Is creating an image based on the String, which isn't associated or connected the String reference.
If you want to manage the images you need to keep an array of images not strings.
Alternately you could use a Dictionary Swift Collection Types
You want to remove the images from the cards?
If the answer is yes, just change the card's image to something else:
You can run this on Playground to understand the logic.