Search code examples
swiftroundingbuilt-in

Calling the built-in function with the same name as a custom function


I have the following code to round a value to any nearest number:

func round(_ value: Double, toNearest nearest: Double) -> Double {
    let roundedValue = round(value / nearest) * nearest
    return roundedValue
}

However, I get the following complaint because I use the same name for this method as the builtin one:

Missing argument for parameter 'toNearest' in call

Is there a way to get around this? i.e. builtin round(value / nearest)?

Thanks.


Solution

  • As shown in the following answer:

    most Darwin/C rounding methods are now readily available as native Swift methods, for types conforming to FloatingPoint (e.g. Double and Float). This means that if you are set on implementing your own rounding method using the same logic as in your question, you can use the rounded() method of FloatingPoint, which make use of the .toNearestOrAwayFromZero rounding rule, which is (as described in the linked answer) equivalent to the Darwin/C round(...) method.

    Applied to modify your custom round(_:toNearest:) function:

    func round(_ value: Double, toNearest nearest: Double) -> Double {
        return (value / nearest).rounded() * nearest
    }