Nexus4life
Nexus4life

Reputation:

Swift println doesn't print array value

I'm brand new learning Swift and I was wondering what I am doing wrong here? I like to play around with code to gain an understanding.

var shoppingList = ["pound of catfish", "bottle of fresh water", "bag of tulips", "can of blue paint"]

println("Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item.")

I'm trying to figure out why the output doesn't say "Susie checks her Shopping List to find that a bag of tulips is her third item." as opposed to what it says currently: exactly as above, "Susie checks her Shopping List to find that a (shoppingList[2]) is her third item."

I know this is an ultra basic concept and all but I want to make sure I understand everything 100%.

Thanks!

Upvotes: 1

Views: 2949

Answers (3)

Tchelow
Tchelow

Reputation: 593

As in Apple docs:

“Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis.”

In your case, the code should be:

println("Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item.")

Upvotes: 0

nwn
nwn

Reputation: 584

The problem here is that you are simply outputting the string "(shoppingList[2])".

To replace this with the value you want, you must first escape the string using a \.

var shoppingList = ["pound of catfish", "bottle of fresh water", "bag of tulips", "can of blue paint"]

"Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item."

This is called String Interpolation and you can find more information here.

Upvotes: 1

Connor
Connor

Reputation: 64644

You need a \ in front of the ().

var shoppingList = ["pound of catfish", "bottle of fresh water", "bag of tulips", "can of blue paint"]

"Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item."

String Interpolation

Upvotes: 0

Related Questions