0

How do I add multiple Strings to one index in an Array? I had:

var cardNamesArray:[String] = ["card5", "card6", "card7", "card8", "card9", "card10", "card11", "card12"]

With, card5 at index 0, card6 at index 1, card7 at index 2, and so on. I want to assign card5, card6, card7, and card 8 to index 0, and card 9, card 10, card11, card12 to index 1. Can someone please tell me how to done this?

Is there any way I can do this without making an Array of Arrays and just assigning the cards to the index value?

var cardNamesArray:[[String]] = [["card5", "card6", "card7", "card8"], ["card9", "card10", "card11", "card12"]]

After making an Array of Arrays, I have only 2 indicies as I need, however I can't seem to call the String later on in Xcode. I have a UIButton randomizing a number and I want to connect the number to an image represented by one of the cards, but I want four of them to be of the same value.

var firstRandomNumber: Int = Int(arc4random_uniform(2))

I run into an error on this line saying

"cannot convert value type '[string]' to specified type 'String'.

var firstCardString: String = self.cardNamesArray[firstRandomNumber]

However when I put a [ ] around String in the first line above, it runs and I incur and error on the next line saying

self.firstCardImageView.image = UIImage(named: firstCardString)

"cannot convert value type '[string]' to expected argument type 'string'."

I would really appreciate any help! Thanks.

2 Answers 2

2

You need to generate random number twice, first one for Array of Array, And second one for your card like this.

var cardNamesArray:[[String]] = [["card5", "card6", "card7", "card8"], ["card9", "card10", "card11", "card12"]]
var firstRandomNumber: Int = Int(arc4random_uniform(2))
var secondRandomNumber: Int = Int(arc4random_uniform(4))
var firstCardString: String = self.cardNamesArray[firstRandomNumber][secondRandomNumber]
self.firstCardImageView.image = UIImage(named: firstCardString)
Sign up to request clarification or add additional context in comments.

Comments

0

You try to get string but your object is a Array that you declared before

var cardNamesArray:[[String]] = [["card5", "card6", "card7", "card8"], ["card9", "card10", "card11", "card12"]]

Change your code to this

var firstObjFromArray: Array = self.cardNamesArray[0]
var firstCardString: String = firstObjFromArray[firstRandomNumber]

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.