Welcome to the Treehouse Community
Looking to learn something new?
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.
Holt Hunter4,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 Schulze12,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.