1

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!

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.