Reputation: 22252
iOS Gesture Recognizers move through different states. It is common (for me at least) to capture reference state at the first beginning state. In ObjectiveC, that might look something like:
- (void)pan:(UIPanGestureRecognizer *)pan {
static NSTimeInterval originalBegin;
static NSTimeInterval originalEnd;
static CGFloat originalYOffset;
if (pan.state == UIGestureRecognizerStateBegan) {
originalBegin = self.timeAxis.begin;
originalEnd = self.timeAxis.end;
originalYOffset = self.yOffset;
}
...
}
But Swift does not have static function variables that preserve values between execution of the function. I can turn these kinds of variables into var
s at the class level, but then it pollutes the variable space of the object, just for variables that are just attached to the particular recognizer.
Is there Swift idiomatic way to capture this pattern locally? Or is this one of those areas where Swift just has friction with UIKit.
Upvotes: 2
Views: 168
Reputation: 1285
In Swift you can nest a struct, class or enum definition within a function and hold static state there from run to run. For example:
func run() {
enum State { static var counter = 0 }
State.counter += 1
print(State.counter)
}
run()
run()
run()
Upvotes: 2