99 Bottles of Beer in Swift

August 21, 2021

In The Passionate Programmer by @chadfowler, Chad recommends solving a challenge in your language. His favorite is creating "99 Bottles of Beer on the Wall" lyrics without using variables. Here's my solution in Swift:

func getRecursiveLyrics(numberOfBottles: Int, originalNumberOfBottles: Int) -> String {
    if numberOfBottles == 0 {
        return "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, \(getBottleNumber(number: originalNumberOfBottles)) bottles of beer on the wall."
    }
    return "\(getBottleNumber(number: numberOfBottles)) bottles of beer on the wall, \(getBottleNumber(number: numberOfBottles)) bottles of beer.\nTake one down and pass it around, \(getBottleNumber(number: numberOfBottles - 1)) bottles of beer on the wall.\n\n" + getRecursiveLyrics(numberOfBottles: numberOfBottles - 1, originalNumberOfBottles: originalNumberOfBottles)
}

func getBottleNumber(number: Int) -> String {
    return number == 0 ? "No more" : "\(number)"
}

func getLyrics(numberOfBottles: Int) -> String? {
    guard numberOfBottles >= 0 else {
        return nil
    }
    return getRecursiveLyrics(numberOfBottles: numberOfBottles, originalNumberOfBottles: numberOfBottles)
}

if let unwrappedLyrics = getLyrics(numberOfBottles: 99) {
    print(unwrappedLyrics)
}

Lyrics