我是Swift的初学者,试图解决循环挑战中的“墙上的99瓶啤酒”。关于这个挑战,我有两个问题。
在下面的代码中,我不明白第二个输入“ totalNumberOfBottles”代表什么。调用函数beerSong()时,我们不会打印或调用此参数,而只会引用forThisManyBottles。它代表什么?它仅仅是forThisManyBottles的另一个副本吗?因此,在for循环中,由于我为瓶子输入的示例编号为5,因此其表示方式等同于:
for number in (1...forThisManyBottles).reversed() {
}
我曾尝试用Swift编程语言完成对Google的类似案例;但是,其中一个是处理case和switch语句的,因此不符合我现在在课程中要学习的逻辑。
func beerSong(forThisManyBottles totalNumberOfBottles : Int) -> String {
var lyric : String = ""
for number in (1...totalNumberOfBottles).reversed() {
let newLine : String = "\n\(number) bottles of beer on the wall, \(number) bottles of beer. \nTake one down and pass it around, \(number - 1) bottles of beer on the wall.\n"
let oneLine : String = "\n\(number) bottle of beer on the wall, \(number) bottle of beer. \nTake one down and pass it around, no bottles of beer on the wall.\n"
let twoLine: String = "\n\(number) bottles of beer on the wall, \(number) bottles of beer. \nTake one down and pass it around, \(number-1) bottle of beer on the wall.\n"
if number == 1 {
lyric += oneLine
}
else if number == 2 {
lyric+=twoLine
}
else {
lyric += newLine
}
}
lyric += "\nNo more bottles of beer on the wall, no more bottles of beer. \nGo to the store and buy some more, \(totalNumberOfBottles) bottles of beer on the wall.\n"
return lyric
}
print(beerSong(forThisManyBottles: 5))
)
//The output of my code is as follows:
//5 bottles of beer on the wall, 5 bottles of beer.
//Take one down and pass it around, 4 bottles of beer on the wall.
//4 bottles of beer on the wall, 4 bottles of beer.
//Take one down and pass it around, 3 bottles of beer on the wall.
//3 bottles of beer on the wall, 3 bottles of beer.
//Take one down and pass it around, 2 bottles of beer on the wall.
//2 bottles of beer on the wall, 2 bottles of beer.
//Take one down and pass it around, 1 bottle of beer on the wall.
//1 bottle of beer on the wall, 1 bottle of beer.
//Take one down and pass it around, no bottles of beer on the wall.
//No more bottles of beer on the wall, no more bottles of beer.
//Go to the store and buy some more, 5 bottles of beer on the wall.