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 trialHarry Stebbings
1,097 PointsRemind me: why do we use a \ on the 2nd line before number?
Why the \
2 Answers
kjvswift93
13,515 Pointsfor number in 1...10 {
println("\(number) * 7 = \(number * 7)")
}
This example is the answer to the For-In Loop Challenge. Essentially the line of code (number) within the println statement is the same thing as saying " 1, 2, 3, 4, 5, 6, 7, 8, 9, 10" each at the beginning of a new line. Then by using (number * 7), you are saying "7, 14, 21, 28, 35," etc.." therefore making each new line read "1 * 7 = 7" , "2 * 7 = 14", "3 * 7 = 21", and so on until the numbers 1 through 10 inclusive have each been multiplied by 7 on a new line.
Omar Kassim
428 PointsI was wondering about this as well and Kyle Vandeven's response above didn't convince me that the backslash in this case created a new line (which is what the println function does). You can test this by removing the backslash character in Kyle's example response to the For-In Loop Challenge:
for number in 1...10 {
println("(number) * 7 = \(number*7)")
}
This results in:
(number) * 7 = 7 (number) * 7 = 14 (number) * 7 = 21 (number) * 7 = 28 (number) * 7 = 35 (number) * 7 = 42 (number) * 7 = 49 (number) * 7 = 56 (number) * 7 = 63 (number) * 7 = 70
The backslash is therefore required to pass the value of number to the println function.
Apple's documentation explains this a bit better:
Roberto Alicata
Courses Plus Student 39,959 PointsRoberto Alicata
Courses Plus Student 39,959 PointsWe use the \ (number) to make a string interpolation to send to the println function