After gesture finishes, my variables get reset to 0

@IBAction func OnRightSwipeGesture(sender: UIPanGestureRecognizer) {
        let translated = sender.translationInView(self.view);
       
        let diffTrans = (translated.y - previouslyTranslated.y) / 75;
        sum += diffTrans;
        print(sum);
        colorWheel.transform = CGAffineTransformMakeRotation(sum);
        previouslyTranslated = translated;
    }

In this code, I'm using a swipe gesture to turn a wheel. It takes the difference in movement between calls and adds them to sum, which then becomes the rotation of the wheel. The problems is, however, that once I have taken my finger off the screen sum gets reset to 0 on the next gesture call even though its a variable declared at the top of the class. I'm somewhat new to swift and in other languages that's called an instance variable. Do they not behave the same way in swift?

Yes, instance variables (aka stored properties) work like you would expect them to, so there must be something else going on.


Do you you reset 'previouslyTranslated' to 0 at the end of the drag/pan (or at the beginning of a new drag/pan)?


If not, that would make it appear as if 'sum' were being reset to 0, since your first 'diffTrans' would be the result of subtracting the whole amount of the previous drag/pan from the first translation of the new drag/pan.

UIPanGestureRecognizer's translationInView returns difference from the starting pan location. So when gesture recognizer's state is Began, it returns zero. Maybe you should set previouslyTranslated to translated value when state is Began:


@IBAction func OnRightSwipeGesture(sender: UIPanGestureRecognizer) {
    let translated = sender.translationInView(self.view)
      
    if sender.state == .Began {
        previouslyTranslated = translated
    }
      
    let diffTrans = (translated.y - previouslyTranslated.y) / 75
    sum += diffTrans
    print(sum);
    colorWheel.transform = CGAffineTransformMakeRotation(sum)
    previouslyTranslated = translated
}


E: Now I realized I'm repeating what LCS said.

After gesture finishes, my variables get reset to 0
 
 
Q