【问题标题】:Calling the built-in function with the same name as a custom function调用与自定义函数同名的内置函数
【发布时间】:2017-12-31 10:52:21
【问题描述】:

我有以下代码将一个值四舍五入为任何最接近的数字:

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)?

谢谢。

【问题讨论】:

标签: swift rounding built-in


【解决方案1】:

如下答案所示:

大多数 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
}

【讨论】:

    猜你喜欢
    • 2011-11-30
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多