Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Swift: String Interpolation

Can someone explain this to me? When do I use this and how do I know when to use it? I've looked online and found some helpful links but I could use some hand holding a bit here. Thanks.

3 Answers

Holt Hunter
Holt Hunter
4,629 Points

String Interpolation is when you want to include a variable in your string, for instance:

var name = "Jason"

println("Hello, \(name)!")

//prints "Hello, Jason!"

This is useful everywhere in programming. For example, say you have a game and at the beginning of the game your user inputs his/her name somewhere, you store the name in a variable "userName". Then as the user is going through the beginning of the game and the app is telling the user how to play, it could say "Now \(userName), press the button in the top right corner...". For the user it makes the app seem more "friendly".

That is just one example of string interpolation but there are many other ways to apply it than just that.

Hope this helps!

Manuel Schulze
Manuel Schulze
12,739 Points

You don't have to use it but it makes coding much easier sometimes.

Instead of writing println("Hello my firstname is: " + variable1 + " and I'm " + variable2 + " years old.") you can make this easier with: println("Hello my firstname is \(variable1) and I'm \(variable2) years old.")

So you don't have to take care about all the quotes and plus operators.

Thanks guys, Holt, that was the best answer but Manuel and Eric that was super useful too.

Holt Hunter
Holt Hunter
4,629 Points

Glad I could help!