1

I have a variable (1) that is either < 0 or 0 >. That value should be added to another value (2) when value (1) is > 0. However value (2) should be subtract by value (1) if that value is < 0, of course making value (1) positive when subtracting. My code looks like this:

positionRandomButton = CGPoint(x: CGFloat(randomXValue) + card.position.x, y: CGFloat(randomYValue) + card.position.y)

Here randomXValue and randomYValue can be that value (1). Now it always adds be, despised value (1) can be < 0. I can solve this by making four if cases, but I think there should be a better method. the +'s you see in the code should change accordingly, or something else should happen. Thanks.

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • Your question is unclear. Try adding a table of values to your question that shows the inputs and what you want the output to be for both cases when variable 1 is positive and negative. – vacawama Apr 06 '17 at 22:01

2 Answers2

1

Subtracting a negative number is the same as adding a positive number. So simply add the absolute value.

positionRandomButton = CGPoint(x: CGFloat(abs(randomXValue)) + card.position.x, y: CGFloat(abs(randomYValue)) + card.position.y)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • This way card.position.x and y would always increase. randomXValue and YValue can be negative, because in that way, I know card.position.x and/or y needs to be substrated by the given (negative) X or YValue. That negative X or Y value needs to be of course converted to positive when subtracting. – J. Doe Apr 06 '17 at 21:22
  • 1
    @J.Doe I have no idea what your comment means. Is my answer what you need or not? – rmaddy Apr 06 '17 at 21:56
1

you can just add the negative value:

var name1 = 10
var name2 = -2
var name3 = name1 + name2 // 10 + (-2) = 8
muescha
  • 1,544
  • 2
  • 12
  • 22