I'm trying to figure out how to declare a static variable scoped only locally to a function in Swift.
In C, this might look something like this:
int foo() {
static int timesCalled = 0;
++timesCalled;
return timesCalled;
}
In Objective-C, it's basically the same:
- (NSInteger)foo {
static NSInteger timesCalled = 0;
++timesCalled;
return timesCalled;
}
But I can't seem to do anything like this in Swift. I've tried declaring the variable in the following ways:
static var timesCalledA = 0
var static timesCalledB = 0
var timesCalledC: static Int = 0
var timesCalledD: Int static = 0
But these all result in errors.
- The first complains "Static properties may only be declared on a type".
- The second complains "Expected declaration" (where
static
is) and "Expected pattern" (wheretimesCalledB
is) - The third complains "Consecutive statements on a line must be separated by ';'" (in the space between the colon and
static
) and "Expected Type" (wherestatic
is) - The fourth complains "Consecutive statements on a line must be separated by ';'" (in the space between
Int
andstatic
) and "Expected declaration" (under the equals sign)