【问题标题】:Using overridden math function使用覆盖的数学函数
【发布时间】:2016-10-18 15:13:27
【问题描述】:

试图编译这段代码

pow(10,2)
struct Test {
  var i:Int
  func pow(_ p:Int) -> Int { return pow(i,p) }
}
var s = Test(i:10)
s.pow(2)

给我一​​个编译器错误。显然,标准的 math.h 函数 pow 被 Swift 的作用域规则蒙蔽了双眼。这有点像编译器错误,因为 pow 的 math.h 版本具有不同的签名。不过,有什么方法可以调用它吗?

【问题讨论】:

  • 这是一个错误 - 请参阅 Swift 3.0: compiler error when calling global func min<T>(T,T) in Array or Dictionary extension。解决方案是使用函数所在的模块名称来消除歧义。
  • 虽然在你的情况下,首先没有 (Int, Int) -&gt; Intpow 重载 - 调用 pow(10,2) 实际上使用重载 (Decimal, Int) -&gt; Decimal
  • pow 返回(并接受)十进制,而不是 Int - 我认为编译器由于类型推断而丢失。这突然起作用了with these annoying modifications,但它确实看起来像一个编译器错误。
  • 确实需要并返回十进制。但即使return Int(pow(Decimal(i),p)) 也不能解决问题。
  • 如何通过浮点:{ return lrint(Darwin.pow(Double(i),Double(p))) }

标签: swift function scope


【解决方案1】:

有两个问题:第一个是pow(i,p)是如何解决的。 如Swift 3.0: compiler error when calling global func min<T>(T,T) in Array or Dictionary extension 中所述,这 可以通过在函数调用前加上模块名称来解决。

第二个问题是没有pow函数 两个整数参数。有

public func powf(_: Float, _: Float) -> Float
public func pow(_: Double, _: Double) -> Double

在标准数学库中,并且

public func pow(_ x: Decimal, _ y: Int) -> Decimal

在基金会图书馆。所以你必须选择使用哪一个, 例如:

struct Test {
    var i:Int
    func pow(_ p:Int) -> Int {
        return lrint(Darwin.pow(Double(i),Double(p)))
    }
}

将参数转换为Double 并对结果进行四舍五入 回Int

或者,使用迭代乘法:

struct Test {
    var i: Int
    func pow(_ p:Int) -> Int {
        return (0..<p).reduce(1) { $0.0 * i }
    }
}

我在https://codereview.stackexchange.com/a/142850/35991 观察到 这对于小指数来说更快。您的里程可能会有所不同。

【讨论】:

    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多