Binary Operator + Cannot be Applied to Operands of

2019-02-25 08:59发布

I am having the same problem as earlier with a different line of code; but this time, I wasn't able to fix it with the same approach as last time:

 var Y : Int = 0
 var X : Int = 0
 @IBOutlet var ball : UIImageView!
 ball.center = CGPointMake(ball.center.x + X, ball.center.y + Y) 

This is the error I am getting:

binary operator + cannot be applied to operands of type CGfloat int

3条回答
劳资没心,怎么记你
2楼-- · 2019-02-25 09:22

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 }
查看更多
Animai°情兽
3楼-- · 2019-02-25 09:25

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
查看更多
Ridiculous、
4楼-- · 2019-02-25 09:39

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))
查看更多
登录 后发表回答