Welcome to the Treehouse Community
Looking to learn something new?
Alex Bargar760 Points
What is the difference between concatenation and interpolation? It seems like you can do the exact same thing with both
You can combine a string and a variable with both. What is the difference then?
Pasan PremaratneTreehouse Teacher
Concatenation allows you to combine to strings together and it only works on two strings. 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. Some code:
//Concatenation works with strings only let str = "Hi, my name is " let anotherString = "Pasan" let myName = str + anotherString // The following line of code won't work. // Paste it in a playground and uncomment it. // var concat = str + 2 /* 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. */ let name = "Pasan" let nameString = "Hi, my name is \(name)" // This also works with non string types let temp = 52 let temperatureDisplay = "The current temperature is \(temp) Farenheit." // You can also replace the evaluation of an expression using string interpolation let celciusTempDisplay = "The current temperature is \((temp-30)/2) Celcius."
Hope this helps.
"Concatenation allows you to combine to strings together and it only works on two strings."
An update. Not sure what earlier versions of Swift allowed, but currently you can concatenate more than 2 Strings together in the same statement:
let str = "Hi, my name is "
var concat = str + "2" + "3" + "4" + "5" + " works" //displays "Hi, my name is 2345 works"
Because both operands of + need to be Strings, you have to do a little extra work if you want to add a number to a String:
var concat2 = str + String(2) //displays "Hi, my name is 2"
Re why interpolation rather than concatenation, here's a quote from Apple's intro for interpolation: "String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions" In other words, you can use interpolation with numbers, booleans, etc. without first turning them into Strings, which you would have to do if you used concatenation.