Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Expression is not assignable" -- Problem assigning float as sum of two other floats in Xcode?

In a piano app, I'm assigning the coordinates of the black keys. Here is the line of code causing the error.

'blackKey' and 'whiteKey' are both customViews

blackKey.center.x = (whiteKey.frame.origin.x + whiteKey.frame.size.width);
like image 992
Mahir Avatar asked Aug 16 '11 06:08

Mahir


2 Answers

The other answers don't exactly explain what's going on here, so this is the basic problem:

When you write blackKey.center.x, the blackKey.center and center.x both look like struct member accesses, but they're actually completely different things. blackKey.center is a property access, which desugars to something like [blackKey center], which in turn desugars to something like objc_msgSend(blackKey, @selector(center)). You can't modify the return value of a function, like objc_msgSend(blackKey, @selector(center)).x = 2 — it just isn't meaningful, because the return value isn't stored anywhere meaningful.

So if you want to modify the struct, you have to store the return value of the property in a variable, modify the variable, and then set the property to the new value.

like image 135
Chuck Avatar answered Sep 20 '22 00:09

Chuck


You can not directly change the x value of a CGPoint(or any value of a struct) like that, if it is an property of an object. Do something like the following.

CGPoint _center = blackKey.center;
_center.x =  (whiteKey.frame.origin.x + whiteKey.frame.size.width);
blackKey.center = _center;
like image 22
EmptyStack Avatar answered Sep 22 '22 00:09

EmptyStack