0

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")

        }

    }

}

}

3 Answers 3

1

You can run this on Playground to understand the logic.

import UIKit
import GameKit

var array1 = ["one", "two"]
var array2 = ["one", "two"]

// Create a helper method to get random int
func getRandomIntFromArray(array: [String]) -> Int {
    return GKRandomSource.sharedRandom().nextIntWithUpperBound(array1.count)
}

var indexA = getRandomIntFromArray(array1)
var indexB = getRandomIntFromArray(array2)

// At snapButtonTapped
// Check the array count first so that you will not get index out of range.
if array1.count > 0 {
    if indexA == indexB {

        // First remove index first
        array1.removeAtIndex(indexA)
        array2.removeAtIndex(indexB)

        // Assign to new random index
        indexA = getRandomIntFromArray(array1)
        indexB = getRandomIntFromArray(array2)

        // After assigned a new random index, set image base on that index
        // FirstCardImageView.image = UIImage(named: array1[indexA])
        // SecondCardImageView.image = UIImage(named: array2[indexB])
    }
} else {
    print("Finished, all array was removed") // Do anything here such as set empty image for FirstCardImageView & SecondCardImageView or success alert.
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for having a look at this, I'm getting an error message "Instance member 'cardNamesArray cannot be used on type 'ViewController' when I assign IndexA = getRandomIntFromArray(array1)
Welcome, glad you got it!
hey, have a look ay my original post I'm getting that "cannot be used on type ViewController" message again. not sure what this means
1

You want to remove the images from the cards?

If the answer is yes, just change the card's image to something else:

if firstRandomNumber == secondRandomNumber {
        //print("index match")
        //self.playRoundTapped(self.PlayRoundButton) <--- I have tried to recall the playRoundTapped method but it doesn't remove the element and goes crazy

            cardNamesArray.removeAtIndex(firstRandomNumber)<----how can I apply this to a UIImage?
            cardNamesArray2.removeAtIndex(secondRandomNumber)
            FirstCardImageView.image = UIImage(named: "someDefaultImage")
            SecondCardImageView.image = UIImage(named: "someDefaultImage")
        } 

6 Comments

instead of "someDefaultImage" how can I change it to the next image in the array?
You already have your current image index, it's the firstRandomNumber and secondRandomNumber. So just take from your images array the image at the next index, something like let image1Name = myImagesArray[firstRandomNumber+1] let image2Name = myImagesArray[secondRandomNumber+1]
Hey, I placed the code underneath removeAtIndex but is telling me to replace "let" with _ let FirstCardImageView = cardNamesArray[firstRandomNumber+1]
You use the _ when you don't need the result of some function. Post your code to make it easier to see what you did
Have a look at my updated code in my original post. I get two problems the first one; the cards change to the next matching pair should be random. The second one I get Array index out of range.
|
0

It appears your array is tracking strings, not images.

This line

 SecondCardImageView.image = UIImage(named: secondCardString)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.