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
Phil Hanson
764 PointsBottles of beer in Swift
I wanted to write code singing the bottle of beer song. The iteration was easy but I didn't have knowledge of who to count down in stead of iterate up. I found an example online but I'm having issues, it just runs forever with no errors and no results. Here is what I have...
//: Playground - noun: a place where people can play
import UIKit
for i in stride(from: 99, to: 0, by: -1) {
if i == 99 {
print("\(i) bottles of beer on the wall, \(i) bottle of beer. You take one down pass it around...")
} else if i < 99 && i > 1 {
print("\(i) bottles of beer on the wall")
print("\(i) bottles of beer on the wall, \(i) bottle of beer. You take one down pass it around...")
} else if i == 1 {
print("\(i) bottle of beer on the wall")
print("\(i) bottle of beer on the wall, \(i) bottle of beer. You take one down pass it around...")
} else {
print("We all pass out drunk!")
}
}
I want the first line, 99, not to have the additional, "Bottle of beer", 98-2, to have the addition, "Bottles of beer", and 1 to only say, "Bottle". I thought I had it perfect but, it's not completing, what am I doing wrong?
Thanks! Happy Swifting.
1 Answer
miguelcastro2
Courses Plus Student 6,573 PointsYour problem was that the loop stops at zero and never finishes, you need to stop the loop at -1 so it processes the last line. You can reduce the code to just a few lines:
for i in stride(from: 99, to: -1, by: -1) {
if (i < 99 && i > 0) {
println("\(i) bottles of beer on the wall.")
}
if (i > 0) {
println("\(i) bottles of beer on the wall, \(i) bottle of beer. You take one down pass it around...")
}
if i == 0 {
println("We all pass out drunk!")
}
}
Phil Hanson
764 PointsPhil Hanson
764 PointsArgh I was so careful and got it all right except that part, slapping myself now. :(
But thanks a lot!
So is \ a new line in a string?
miguelcastro2
Courses Plus Student 6,573 Pointsmiguelcastro2
Courses Plus Student 6,573 Pointsprintln(); Adds a new line to each statement.