调用与自定义函数同名的内置函数

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

我有以下代码可以将值舍入到任何最接近的数字:

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

但是,我收到以下投诉,因为我为此方法使用了与内置方法相同的名称:

Missing argument for parameter 'toNearest' in call

有办法解决这个问题吗?即 builtin round(value / nearest)?

谢谢。

如下回答所示:

  • How to round a Double to the nearest Int in swift?

大多数 Darwin/C 舍入方法现在可以作为原生 Swift 方法使用,适用于符合 FloatingPoint 的类型(例如 DoubleFloat)。这意味着如果您打算使用与问题中相同的逻辑实现自己的舍入方法,则可以使用 rounded() method of FloatingPoint,它利用 .toNearestOrAwayFromZero 舍入规则,即(如所述在链接的答案中)相当于 Darwin/C round(...) 方法。

已应用于修改您的自定义 round(_:toNearest:) 函数:

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