【发布时间】: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) -> Int的pow重载 - 调用pow(10,2)实际上使用重载(Decimal, Int) -> Decimal -
pow返回(并接受)十进制,而不是 Int - 我认为编译器由于类型推断而丢失。这突然起作用了with these annoying modifications,但它确实看起来像一个编译器错误。 -
确实需要并返回十进制。但即使
return Int(pow(Decimal(i),p))也不能解决问题。 -
如何通过浮点:
{ return lrint(Darwin.pow(Double(i),Double(p))) }?