简体   繁体   中英

How do I append an int value into a string array in Swift?

I'm learning Swift now (with basic programming know-how), and I'm making a String array containing a deck of 52 cards via a for loop, but I'm not sure how to append a value with an int and string values.

I know using \\(int) converts an int to a string, but it doesn't seem to work when appending to an array. My code, including the error messages are below:

var suits = ["Spades", "Hearts", "Clubs", "Diamonds"]

var deck:[String] = []    

for s in suits
{

    deck.append("Ace of " + s)
    deck.append("King of " + s)
    deck.append("Queen of " + s)
    deck.append("Jack of " + s)

    for (var i = 2; i < 11; ++i)
    {
        deck.append(\(i) + " of " + s) 
        //error message: "Expected ',' separator"
        //error message: "Invalid character in source file"
    }
}

You need to have your (i) in quotes in order for it to be converted to a String.

deck.append("\(i)" + " of " + s) 

You could also do this:

var value = String(i)
deck.append(value + " of " + s) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM