Static Function Variables in Swift

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)
+75
function static swift
Aug 18 '14 at 0:23
source share
3 answers

I do not think that Swift supports a static variable without binding to a class / structure. Try declaring a private structure with a 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 
+117
Aug 18 '14 at 0:28
source share

Another solution

 func makeIncrementerClosure() -> () -> Int { var timesCalled = 0 func incrementer() -> Int { timesCalled += 1 return timesCalled } return incrementer } let foo = makeIncrementerClosure() foo() // returns 1 foo() // returns 2 
+22
Sep 21 '14 at 10:34
source share

Swift 1.2 with Xcode 6.3 now supports static as expected. From the Xcode 6.3 release notes:

"static" methods and properties are now allowed in classes (as an alias for the "final class"). Now you are allowed to declare static property data in classes that have global storage and are lazily initialized at first access (for example, global variables). Protocols now declare type requirements as "static" requirements instead of declaring them as "cool" requirements. (17198298)

It seems that functions cannot contain static declarations (as asked in the question). Instead, the declaration should run at the class level.

A simple example showing a static property added inside a class function (aka static), although the class function is not required:

 class StaticThing { static var timesCalled = 0 class func doSomething() { timesCalled++ println(timesCalled) } } StaticThing.doSomething() StaticThing.doSomething() StaticThing.doSomething() 

Output:

 1 2 3 
+19
Feb 10 '15 at 7:38
source share



All Articles