Oleg Savelyev
Oleg Savelyev

Reputation: 275

Binary operator '-' cannot be applied to two 'CGFloat' operands

I'm writing 3D game and trying to write expression in the handler of the extracted taps:

  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent!) {

    for touch: AnyObject in touches {
        let touchPoint: CGPoint  = touch.location(in: self)

         if (isTracking == true && sqrtf(powf((touchPoint.x - thumbNode.position.x), 2) + powf((touchPoint.y - thumbNode.position.y), 2)) < size * 2)
        {...}
     }
  }

But Xcode wrote error:

Binary operator '-' cannot be applied to two 'CGFloat' operands.

Than tried:

 var arg_3 = (touchPoint.x - self.anchorPointInPoints().x)
 var expr_3 = powf(Float(arg_3), 2)
 var arg_4 = (touchPoint.y - self.anchorPointInPoints().y)
 var expr_4 = powf(Float(arg_4),2)
 var expr_5 = expr_3 + expr_4
 var expr_6 = thumbNode.size.width

 if (sqrtf(Float(expr_5)) <= expr_6)
 {}

Now it wrotes:

Binary operator '<=' cannot be applied to operands of type 'Float' and 'CGFloat'

Please help me to fix that problem.

Thanks in advance.

Upvotes: 1

Views: 2822

Answers (2)

CRD
CRD

Reputation: 53010

You can use pow and sqrt which take and return CGFloat, which is the type of the values in your CGPoint. This avoids the use of any casts in your sample as everything will be CGFloat.

Upvotes: 1

shallowThought
shallowThought

Reputation: 19602

This is a missleading (wrong) error message.

powf does not accept CGFloats as parameters.

Create a Float instead:

let x = Float(touchPoint.x - thumbNode.position.x)
powf(x, 2)

EDIT:

Solution approach 1:

let y = Float(touchPoint.y - thumbNode.position.y)
let x = Float(touchPoint.x - thumbNode.position.x)
if (isTracking == true && sqrtf(powf(x, 2) + powf(y, 2)) < size * 2)
    {...}

Solution approach 2:

if (sqrtf(Float(expr_5)) <= Float(expr_6)) ...

Upvotes: 0

Related Questions