重载 Swift 轮函数导致 "Could not find an overload for 'init' that accepts the supplied arguments" 错误

Overloading Swift round function results in "Could not find an overload for 'init' that accepts the supplied arguments" error

我是 Swift 的新手,刚刚开始学习一些教程。我决定尝试使用 round 函数修改其中一个的结果,但发现您无法指定小数点后两位,因此我需要使用公式 round(100 * x) / 100。我决定尝试使用以下代码重载 round 函数:

func round(x : Double, precision : Int) -> Double {
    return round(pow(10.0,Double(precision)) * x) / pow(10.0,Double(precision))
}

当我在操场上 运行 这段代码时,它工作得很好。但是,当我将此代码放入我的 xcode 项目时,return 行给出错误 "Could not find an overload for 'init' that accepts the supplied arguments"。我已经导入了 UIKit,所以我不知道为什么它在操场上有效,但在我的程序中却无效。有什么想法吗?

编辑:好吧,再看一遍之后,我确实注意到我在 playground 中的代码与项目中的代码之间的唯一区别是在 playground 中,该函数是在 class,而在项目中它位于 class 中。将项目中的代码移到 class 之外解决了这个问题。所以现在我的问题是,为什么它是否在 class 中很重要?有没有办法让它在 class 中工作?

您将方法 放入 一个 class 定义中,因此它是 编译为 class 的方法。在这种情况下,内部调用 to round() 也被解释为相同 class.

的方法调用

您可以通过指定模块名称来解决这个问题(在本例中为 "Darwin") 明确地:

func round(x : Double, precision : Int) -> Double {
    return Darwin.round(pow(10.0, Double(precision)) * x) / pow(10.0, Double(precision))
}

但更简单的解决方案是将其定义为自由函数,在外部 任何 class.