【发布时间】:2015-04-26 11:43:16
【问题描述】:
我创建了这个infix operator ^^ 来替代使用pow 函数:
infix operator ^^ { associativity left precedence 155 }
func ^^ <T: IntegerLiteralConvertible>(left: T, right: T) -> T {
return pow(left as Double, right as Double)
}
我使用IntegerLiteralConvertible 协议作为泛型left 和right 的类型约束,因为根据我的理解this diagramm 表明,它基本上包括所有数字类型。
为了使用pow 函数,我必须将left 和right 向下转换为Double,我使用as 操作符来做到这一点。这不是最安全的方法,但这不是重点。
在实现功能时this way swift告诉我:
<stdin>:4:12: error: cannot invoke 'pow' with an argument list of type '(Double, Double)'
return pow(left as Double, right as Double)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
现在据我所知pow 需要两个Doubles 作为参数,那它为什么抱怨这个呢?
【问题讨论】:
-
2019 年您好! .现在,我在 Foundation for pow 中看到了这个声明:
public func pow(_ x: Decimal, _ y: Int) -> Decimal
标签: swift generics pow downcast type-constraints