0

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

1 Answer 1

3

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I'm glad it was a simple thing. Now on to newer bugs... :)
Easiest solution is just to put it all in one string: "\(i) of \(s)" In general putting expressions to be evaluated into a string like this is referred to as "String Interpolation" @Dodgepodge, you might want to check it out in the Swift manual.
You're right, @DavidBerry - somehow that slipped my mind, even though I did that at some point in other code below this snippet. I try to read the Swift manual when I can, but as a beginner, I find it a bit too overwhelming. I will keep reading though, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.