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.
static
is) and "Expected pattern" (where timesCalledB
is)static
) and "Expected Type" (where static
is)Int
and static
) and "Expected declaration" (under the equals sign)I don't think Swift supports static variable without having it attached to a class/struct. Try declaring a private struct with static variable.
func foo() -> Int {
struct Holder {
static var timesCalled = 0
}
Holder.timesCalled += 1
return Holder.timesCalled
}
7> foo()
$R0: Int = 1
8> foo()
$R1: Int = 2
9> foo()
$R2: Int = 3