Swift中运算符' - '与'abs()'的模糊使用

时间:2015-12-12 12:41:06

标签: swift

我正在尝试执行以下操作:

var i = -(abs(-3))

var i = -abs(-3)

var i = -abs(3)

var i = -(abs(3))

但是我得到一个错误,说使用减号是模棱两可的。为什么呢?

2 个答案:

答案 0 :(得分:5)

对我来说,这看起来像编译器错误,文字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作为参数来解决此问题:

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

答案 1 :(得分:2)

我同意@MartinR这看起来像编译器错误。那么问题出在哪里?

我的实验指出一元减去是罪魁祸首。请注意,即使:

var i = -(3)

失败了:

error: ambiguous use of operator '-'
var i = -(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: CoreGraphics.CGFloat) -> CoreGraphics.CGFloat**

这个简单的表达方式:

var i = -(3 + 2)

失败了:

error: ambiguous use of operator '+'
var i = -(3 + 2)
            ^
Swift.+:2:13: note: found this candidate
public func +(lhs: Float, rhs: Float) -> Float
            ^
Swift.+:2:13: note: found this candidate
public func +(lhs: Double, rhs: Double) -> Double
            ^
Swift.+:2:13: note: found this candidate
public func +(lhs: Float80, rhs: Float80) -> Float80
            ^
CoreGraphics.+:2:13: note: found this candidate
public func +(lhs: CoreGraphics.CGFloat, rhs: CoreGraphics.CGFloat) -> CoreGraphics.CGFloat

每次都有四种类型 Float Double Float80 CoreGraphics.CGFloat 斯威夫特难以决定。为什么只有这四个? 为什么那里没有Int?特别是因为Swift默认将整数文字视为Int