Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Basics Swift Types Strings

Understanding the correct use of String Interpolation?

Hello, it appears I was stuck on the quiz question because I typed the code as:

  let name = "Natia"
  let greeting = "Hi there"

  let interpolatedGreeting = "\(greeting), \(name)"

But after reading you guys questions here I learned the correct way to type is:

  let name = "Natia"
  let greeting = "Hi there, \(name)"

when put into Xcode both printed the correct results. However, the quiz only accepted the second version.. which is weird because in the video he only showed us the first way? Can someone help me better understand why it is "correct" to write it the second way? And which is better practice?

Now that I think about it, is it because the name changes so it therefore needs a line of code. Whereas the greeting "Hi there" will likely not change so it therefore does not need a line of code, but can instead just be written into the actual string interpolation itself?

1 Answer

I can't speak to the particulars of the Swift language, since I have no experience with it. But based on how I've encountered string interpolation in Python and JavaScript, for instance, it would appear like you have correctly answered your own question. The name variable is the dynamic (changing) part of the string, and as such requires the interpolation. The greeting itself would appear to be static/unchanging (with "Hi there", I guess, being asked of any user...), and hence acceptable in "literal" (i.e. un-interpolated) form.

Short version of my ramble above: you answered your own question perfectly.

Thanks! And yes it definitely took me writing out the question to realize I may already subconsciously understood the answer, but wanted to verify! Thank you for your input!