2017-07-25 134 views
1

我有下面的代码将值四舍五入到任何最接近的数字:调用具有相同名称为自定义功能的内置函数

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)

谢谢。

+1

您是否尝试过'Darwin.round(价值/最近)'? – OOPer

+1

供参考具有通过其签名进行区分的具有相同名称的多个函数称为函数重载。 – Balanced

+0

相关:[Swift 3.0:调用全局func min (T,T)时数组或字典扩展中的编译器错误](https://stackoverflow.com/q/39602298/2976878)&[Xcode 8 Beta 4 Swift 3 - “圆”行为改变](https://stackoverflow.com/q/38767635/2976878) – Hamish

回答

1

如在下面的答案所示:

最达尔文/ C舍入现在的方法很容易得到作为本机夫特方法,符合FloatingPoint(例如DoubleFloat)类型。这意味着如果您设置为使用与您的问题中相同的逻辑来实现自己的舍入方法,则可以使用rounded() method of FloatingPoint,它使用.toNearestOrAwayFromZero舍入规则,该舍入规则等同于(在链接答案中描述的)舍入规则达尔文/ C round(...)方法。

适用于修改自定义round(_:toNearest:)功能:

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

这是一种魅力。谢谢您的回答。 – Alex

0

为什么你需要相同的名称,你不能只是将它重命名为roundTo():p。

我相信你可以有两个同名的函数,只要它们有不同的类型或参数标签。尝试更改参数?

相关问题