Binary operator '+' cannot be applied to two CGFloat operands?

跟風遠走 提交于 2019-12-21 03:14:20

问题


Coding in Swift and get the above error...

Is the message masking something else OR can you really not add two CGFloat operands? If not, why (on earth) not?

EDIT

There is nothing special in the code I am trying to do; what is interesting is that the above error message, VERBATIM, is what the Swift assistant compiler tells me (underlining my code with red squiggly lines).

Running Xcode 6.3 (Swift 1.2)


回答1:


It's absolutely possible, adding two CGFloat variables using the binary operator '+'. What you need to know is the resultant variable is also a CGFloat variable (based on type Inference Principle).

let value1 : CGFloat = 12.0
let value2 : CGFloat = 13.0
let value3   = value1 + value2
println("value3 \(value3)")

//The result is value3 25.0, and the value3 is of type CGFloat.

EDIT: By Swift v3.0 convention

let value = CGFloat(12.0) + CGFloat(13.0)
println("value \(value)")

//The result is value 25.0, and the value is of type CGFloat.



回答2:


I ran into this using this innocent-looking piece of code:

func foo(line: CTLine) {
    let ascent: CGFloat
    let descent: CGFloat
    let leading: CGFloat
    let fWidth = Float(CTLineGetTypographicBounds(line, &ascent, &descent, &leading))
    let height = ceilf(ascent + descent)
    //                 ~~~~~~ ^ ~~~~~~~
}

And found the solution by expanding the error in the Issue Navigator:

Looking into it, I think Swift found the +(lhs: Float, rhs: Float) -> Float function first based on its return type (ceilf takes in a Float). Obviously, this takes Floats, not CGFloats, which shines some light on the meaning of the error message. So, to force it to use the right operator, you gotta use a wrapper function that takes either a Double or a Float (or just a CGFloat, obviously). So I tried this and the error was solved:

    // ...
    let height = ceilf(Float(ascent + descent))
    // ...

Another approach would be to use a function that takes a Double or CGFloat:

    // ...
    let height = ceil(ascent + descent)
    // ...

So the problem is that the compiler prioritizes return types over parameter types. Glad to see this is still happening in Swift 3 ;P




回答3:


Mainly two possible reasons are responsible to occur such kind of error.

first:

Whenever you try to compare optional type CGFloat variable like

if a? >= b?
   {
     videoSize = size;
   }

This is responsible for an error so jus make it as if a! >= b!{}

Second: Whenever you direct use value to get a result at that time such kind of error occure

like

var result = 1.5 / 1.2

Don't use as above.
use with object which is declare as a CGFloat

like

var a : CGFloat = 1.5
var b : CGFloat = 1.2
var result : CGFloat!
result = a / b


来源:https://stackoverflow.com/questions/28670378/binary-operator-cannot-be-applied-to-two-cgfloat-operands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!