“Expression is not assignable” — Problem assigning float as sum of two other floats in Xcode?

我的未来我决定 提交于 2020-01-09 02:14:15

问题


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);

回答1:


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.




回答2:


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;



回答3:


blackKey.center = CGPointMake ( whiteKey.frame.origin.x + whiteKey.frame.size.width, blackKey.center.y);

One way of doing it.




回答4:


One alternative using macros:

#define CGPOINT_SETX(point, x_value) { \
    CGPoint tempPoint = point;         \
    tempPoint.x = (x_value);           \
    point = tempPoint;                 \
}

#define CGPOINT_SETY(point, y_value) { \
    CGPoint tempPoint = point;         \
    tempPoint.y = (y_value);           \
    point = tempPoint;                 \
}

CGPOINT_SETX(blackKey.center, whiteKey.frame.origin.x + whiteKey.frame.size.width);

or slightly simpler:

CGPOINT_SETX(blackKey.center, CGRectGetMaxX(whiteKey.frame));



回答5:


As its meanings, you can't assign value to expression. For instance, a + b = c it is forbidden.



来源:https://stackoverflow.com/questions/7074405/expression-is-not-assignable-problem-assigning-float-as-sum-of-two-other-fl

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