Binary Operator + Cannot be Applied to Operands of Type CGfloat int

前提是你 提交于 2019-12-01 21:00:14

Declare them, instead, as the following:

let X : CGFloat = 0.0
let Y : CGFloat = 0.0

Replying to your comment:

The error has nothing to do with them being declared as var or let. You could declare them as var and if you so insist on declaring them as Int, you would still need to do the following:

var X : Int = 0
var Y : Int = 0
ball.center = CGPointMake(view.center.x + CGFloat(X), view.center.y + CGFloat(Y))

The problem is that you are not having the same variable types, for example you can't add bool and string.

Change it to CGFloat instead of int:

let X : CGFloat = 0.0
let Y : CGFloat = 0.0

ball.center.x is a CGFloat and X is an Int. That's where the compiler is complaining.

Swift likes you to type cast numeric types (as if there wasn't a hierarchy in numeric domains) but you can avoid that by declaring X and Y as CGFloat instead of Int.

You could also get rid of the issue for good by defining the operator (that Swift should already have imho):

infix operator + {}

func +(left:CGFloat, right:Int) -> CGFloat
{ return left + CGFloat(right) } 

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