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 trialFrances Angulo
5,311 Pointsescaped variable references vs. 'standard'?
Not sure I understand why I'd choose one of the following methods over the other:
println("To build an iPhone app we need to learn \(modernProgrammingLanguage)")
vs.
println("To build an iPhone app we need to learn " + modernProgrammingLanguage)
2 Answers
Stone Preston
42,016 Pointsthe first line is using interpolation, although it has a syntax error. when using interpolation you use a backlash before the ()
println("To build an iPhone app we need to learn \(modernProgrammingLanguage)")
the second just adds the value of the variable onto the end of the string
println("To build an iPhone app we need to learn " + modernProgrammingLanguage)
interpolation is generally easier to use because when using the + operator to concatenate strings together, you have to worry about including spaces between words and stuff like that
println("To build an iPhone app we need to learn " + modernProgrammingLanguage + " " + someOtherVariable)
as you can see I had to concatenate a space in there as well.
interpolation makes it easier to build strings and not have to worry about formatting issues
println("To build an iPhone app we need to learn \(modernProgrammingLanguage) \(someOtherVariable)")
Frances Angulo
5,311 PointsOk! So the results are essentially the same, but one introduces a convenience factor for developers in terms of formatting cleanliness in the output?
Stone Preston
42,016 PointsYes the results are the same its just interpolation is easier to use