2

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.

ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • 1
    Have you tried `Darwin.round(value / nearest)`? – OOPer Jul 25 '17 at 13:28
  • 1
    FYI Having multiple functions with the same name that are distinguished by their signature is called function overloading. –  Jul 25 '17 at 13:34
  • Related: [Swift 3.0: compiler error when calling global func min(T,T) in Array or Dictionary extension](https://stackoverflow.com/q/39602298/2976878) & [Xcode 8 Beta 4 Swift 3 - “round” behaviour changed](https://stackoverflow.com/q/38767635/2976878) – Hamish Jul 25 '17 at 14:11

1 Answers1

1

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
}
dfrib
  • 70,367
  • 12
  • 127
  • 192