我正在尝试执行以下操作:
var i = -(abs(-3))
要么
var i = -abs(-3)
要么
var i = -abs(3)
要么
var i = -(abs(3))
但我得到一个错误,说使用减号是模棱两可的.为什么?
这对我来说看起来像编译器错误,文字的类型3
应该是Int
.但是编译器抱怨道
error: ambiguous use of operator '-' var i = -(abs(-3)) ^ Swift.-:2:20: note: found this candidate prefix public func -(x: Float) -> Float ^ Swift.-:2:20: note: found this candidate prefix public func -(x: Double) -> Double ^ Swift.-:2:20: note: found this candidate prefix public func -(x: Float80) -> Float80 ^ CoreGraphics.-:2:20: note: found this candidate prefix public func -(x: CGFloat) -> CGFloat
您可以使用显式Int
as参数来解决它:
var i = -(abs(-Int(3)))
或者在结果上使用类型注释:
var i : Int = -(abs(-3))
正如@vacawama所注意到的,还有更多可能的解决方案.转换任何子表达式Int
使编译器开心:
var i1 = -(abs(-(3 as Int))) var i2 = -(abs((-3) as Int)) var i3 = -(abs(-3) as Int) var i4 = -(abs(-3)) as Int