我是编程新手,想知道是否有比我在这里所做的更简洁的方法来完成最后的语法编辑(确保它不会返回像 1 bottlesS 这样的无意义语句)?我在想也许是一个 switch 语句,但我还不够熟悉,无法实现一个,甚至无法确定这是否是最好的方法。谢谢!
func beerSong(withThisManyBottles totalNumberOfBottles : Int) -> String {
var lyrics : String = ""
for i in (3...totalNumberOfBottles).reversed() {
let newLine : String = "\n \(i) bottles of beer on the wall, \(i) bottles of beer. \n Take one down and pass it around, \(i - 1) bottles of beer on the wall.\n"
lyrics += newLine
}
lyrics += "\n 2 bottles of beer on the wall, 2 bottles of beer. \n Take one down and pass it around, 1 bottle of beer on the wall.\n"
lyrics += "\n 1 bottle of beer on the wall, 1 bottle of beer. \n Take one down and pass it around, no more bottles of beer on the wall.\n"
lyrics += "\n No more bottles of beer on the wall, no more bottles of beer. \n Go to the store and buy some more, 99 bottles of beer on the wall.\n"
return lyrics
}
print(beerSong(withThisManyBottles : 99))
最佳答案
这是我的看法。 rmaddy 的代码为大多数数字计算了两次 beerBottleLine(for:)
(一次是当数字是“主要”数字时,另一次是当它是“少一个”数字时)。不可否认,这是一个绝对微小且本质上毫无意义的性能差异,但它展示了简洁的 zip(a, a.dropLast())
模式的使用。
我还选择通过利用多行字符串文字、切换到更传统的标识符名称以及使用开关而不是 3 部分 if
/else if
来提高可读性>/else
阶梯。
func bottlePhrase(for count: Int) -> String {
switch count {
case 0: return "no more bottles of "
case 1: return "1 bottle"
case _: return "\(count) bottles"
}
}
func beerSong(bottleCount: Int) -> String {
let bottlePhrases = (0...bottleCount)
.lazy
.reversed()
.map{ bottlePhrase(for: $0) + " of beer" }
let mainBody = zip(bottlePhrases, bottlePhrases.dropFirst())
.map { bottlePhrase, oneLessBottlePhrase in return """
\(bottlePhrase) on the wall, \(bottlePhrase).
Take one down and pass it around, \(oneLessBottlePhrase) on the wall.
"""
}
.joined(separator: "\n")
return mainBody + """
\nNo more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, \(bottleCount) bottles of beer on the wall.
"""
}
print(beerSong(bottleCount: 5))
关于快速切换语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51276323/