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

Sam picture Sam · Feb 23, 2015 · Viewed 24.1k times · Source

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)

Answer

Suresh Kumar Durairaj picture Suresh Kumar Durairaj · Feb 23, 2015

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.