Can't convert value of type '[String]?' to the expected type of the argument 'String'

I want to make the image firstCardequal to the image file with a name that matches firstCardString.

For example, in the example below, the code can be set self.firstCard.imageto display an image named "card1" if it accidentally selects it (I cut 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 get the following error:

Can't convert value of type '[String]?' to the expected type of the argument 'String'

I'm not quite sure what this error message means, what is it [String]??

+4
source share
3 answers

[] - , ? . firstCardString , . deckArray , , firstCardString : Optional(["Bear", "Ball"]). , :

self.firstCard.image = UIImage(named: "card\(firstRandomNumber)")

, "card1" "card4". , - , . , , :

if let cardArray = deckArray["card\(firstRandomNumber)"] {
    //do something with bears and balls
}

deckArray ( ), . :

let cardArray = deckArray[firstRandomNumber]
//do something with bears and balls
+6

, deckArray - , , . , firstRandomNumber = 1, deckArray["card\(firstRandomNumber)"] ["Bear","Ball"]. !

0

Your deckArray is a dictionary, and your firstCardString is an array.

String = String

[String] = Array of strings.
0
source

Source: https://habr.com/ru/post/1613265/


All Articles