What I want to do is set the image of firstCard
to be equal to the image file with the name corresponding to firstCardString
.
For instance, in the case below, the code could be setting self.firstCard.image
to show the image named "card1" if it randomly picks it (I've clipped the rest of the array for brevity, the full thing contains 52 objects).
var deckArray = [
"card1": ["Bear","Ball"],
"card2": ["Bear","Ball"],
"card3": ["Bear","Ball"],
"card4": ["Bear","Ball"],
"card5": ["Bear","Ball"],
"card6": ["Bear","Ball"],
"card7": ["Bear","Ball"],
]
let firstRandomNumber = Int(arc4random_uniform(52))+1
let firstCardString = deckArray["card\(firstRandomNumber)"]
self.firstCard.image = UIImage(named: firstCardString)
Instead, I'm getting the following error:
Cannot convert value of type '[String]?' to expected argument type 'String'
I'm not entirely sure what this error message means, what is [String]?
?
[]
is an array, and ?
is an optional. Your firstCardString
is not a string at all, but an optional array of strings. You've read the deckArray
dictionary's value for that card, you see, and so your firstCardString
actually looks something like this: Optional(["Bear", "Ball"])
. I think you meant:
self.firstCard.image = UIImage(named: "card\(firstRandomNumber)")
This will set the image based on strings like "card1"
or "card4"
. I assume you'll use your dictionary for something else, later. When you do, be sure to unwrap the optional value it returns:
if let cardArray = deckArray["card\(firstRandomNumber)"] {
//do something with bears and balls
}
Alternatively, consider making deckArray
an array (which will make the name more reasonable), rather than a dictionary. Then you won't have to deal with optionals and will be able to access items as follows:
let cardArray = deckArray[firstRandomNumber]
//do something with bears and balls
Your deckArray is a Dictionary, and your firstCardString is an Array.
String = String
[String] = Array of strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With