我正在尝试执行以下操作:
var i = -(abs(-3))
Run Code Online (Sandbox Code Playgroud)
要么
var i = -abs(-3)
Run Code Online (Sandbox Code Playgroud)
要么
var i = -abs(3)
Run Code Online (Sandbox Code Playgroud)
要么
var i = -(abs(3))
Run Code Online (Sandbox Code Playgroud)
但我得到一个错误,说使用减号是模棱两可的.为什么?
这对我来说看起来像编译器错误,文字的类型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
Run Code Online (Sandbox Code Playgroud)
您可以使用显式Intas参数来解决它:
var i = -(abs(-Int(3)))
Run Code Online (Sandbox Code Playgroud)
或者在结果上使用类型注释:
var i : Int = -(abs(-3))
Run Code Online (Sandbox Code Playgroud)
正如@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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
971 次 |
| 最近记录: |