iOS Swift Basics Swift Types String Manipulation

I don't understand

I don't understand why this is not an interpolated string

// Enter your code below
let name = "Morgan"
let greeting = "\(Hi there,), \(name)"

1 Answer

Alex Koumparos
Alex Koumparos
Python Web Development Techdegree Student 35,923 Points

Hi Morgan,

The error is in the first part of the string. Remember that with string interpolation, you are asking the compiler to evaluate anything inside \( ) as Swift code, and then render the result as part of the string.

In the latter part of your string you have "... \(name)". Thus you are telling Swift, "evaluate the name variable, and put the result (i.e., the contents of the variable) inside the string". Swift will look at the name variable, find the value "Morgan" and put that into the string.

Now let's look at the first part of your string, you have "\(Hi there,) ...". You are telling Swift to evaluate Hi there, as Swift code, but since this isn't valid Swift code (it's just part of the string text), Swift is going to complain that there is a syntax error.

When using string interpolation, only put the code you want evaluated inside the \( ), leave everything else inside the regular string.

Hope that helps.



Thank you! That makes perfect sense now. “Code evaluated” was the explanation that made this clear for me.