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
Melissa Du
Courses Plus Student 1,905 PointsWhat's the point of string interpolation? (Swift)
Consider the two following chunks of code:
let language = "Swift" println("Learning " + language)
let language = "Swift" println("Learning (language)")
Both will output "Learning Swift". What's the advantage of using string interpolation (the second example) over the first?
2 Answers
Jhoan Arango
14,575 PointsHello Melissa:
The first example you are showing is called string concatenation, which puts 2 strings together, the other example is String interpolation.
“String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash:”
Hope that helps you answer your questions. If not please let me know and I can go into more depth.
Enrique Munguía
14,311 PointsOne case where string interpolation is very useful is when you want to concatenate a string and another type such as int
let num = 10
print("Num is "+ num) // error
print("Num is \(num)") // correct
Melissa Du
Courses Plus Student 1,905 PointsMelissa Du
Courses Plus Student 1,905 PointsOH. So string interpolation / string concatenation are two completely disparate things. Got it. Thanks!