I am trying to figure out how to declare a static variable locally bound to a function in Swift.
In C, it might look something like this:
int foo() { static int timesCalled = 0; ++timesCalled; return timesCalled; }
In Objective-C, it is basically the same:
- (NSInteger)foo { static NSInteger timesCalled = 0; ++timesCalled; return timesCalled; }
But I can’t do anything like this in Swift. I tried to declare a variable in the following ways:
static var timesCalledA = 0 var static timesCalledB = 0 var timesCalledC: static Int = 0 var timesCalledD: Int static = 0
But all this leads to errors.
- The first complains: "Static properties can only be declared for a type."
- The second complains about "Expected declaration" (where
static is) and "Expected template" (where timesCalledB ) - The third complains: "Sequential statements on a line must be separated"; "(in the space between the colon and
static ) and" Expected type "(where static ) - A fourth complains: "Sequential statements on a line must be separated"; "(between
Int and static ) and" Expected Declaration "(under the equal sign)
function static swift
nhgrif Aug 18 '14 at 0:23 2014-08-18 00:23
source share