How to make sure recursion is optimized?

Can the compiler optimize the recursive calls in the toNearestOr cases? Or should I define an internal roundedTowardsZero function?

func rounded(_ rule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Int {
    // Some computation I don't want repeated for each call...
    switch rule {
    case .toNearestOrAwayFromZero:
        if //... {
            return rounded(.towardZero)
        }
        return rounded(.awayFromZero)
    case .toNearestOrEven:
        if //... {
            return rounded(.awayFromZero)
        }
        return rounded(.toNearestOrAwayFromZero)
    case .up:
        return //...
    case .down:
        return //...
    case .towardZero:
        return //...
    case .awayFromZero:
        return //...
    @unknown default:
        fatalError("Unsupported rounding rule \(rule).")
    }
}

In principle the compiler might be able to optimize the recursive calls, but to be sure you'd have to construct the specific example and then observe it.

1 Like