Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function variables in Swift

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" (where timesCalledB is)
  • The third complains "Consecutive statements on a line must be separated by ';'" (in the space between the colon and static) and "Expected Type" (where static is)
  • The fourth complains "Consecutive statements on a line must be separated by ';'" (in the space between Int and static) and "Expected declaration" (under the equals sign)
like image 207
nhgrif Avatar asked Aug 18 '14 00:08

nhgrif


People also ask

What are static functions in Swift?

A static method is of class type (associated with class rather than object), so we are able to access them using class names. Note: Similarly, we can also create static methods inside a struct. static methods inside a struct are of struct type, so we use the struct name to access them.

Where static variables are stored in Swift?

data segment stores Swift static variables, constants and type metadata.

What is a static variable in a function?

A static variable is a variable that is declared using the keyword static. The space for the static variable is allocated only one time and this is used for the entirety of the program. Once this variable is declared, it exists till the program executes.


Video Answer


1 Answers

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 
like image 52
Bryan Chen Avatar answered Sep 18 '22 23:09

Bryan Chen