快速切换语句

标签 swift for-loop switch-statement

我是编程新手,想知道是否有比我在这里所做的更简洁的方法来完成最后的语法编辑(确保它不会返回像 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/

相关文章:

c# - 什么是大型开关盒的良好替代品?

java - For 循环将自定义对象添加到 arraylist n 次 - Java8

c - 当我编译我的程序时,为什么它会提示 "label at end of compound statement"?

ios - 没有结果时隐藏海关部分?

json - 从选择图像或按钮获取 JSON url 到 Swift 4 中的字符串

python - 在 Python 中仅打印以逗号和空格分隔的列表中的数值

javascript - 有没有办法在循环中对我的 javascript 函数进行编号?

c - 此源代码在 C 中打开一个字符串。它是如何做到的?

ios - UIImageView:AspecT Fit 无法与 UIScrollView 一起使用以将其缩放到全宽

ios - 在 Xcode 中更改 Firebase Crashlytics 的 bundle ID