Swift 中的静态函数变量

我试图弄清楚如何声明一个静态变量的作用域仅限于 Swift 中的一个函数。

在 C 语言中,这可能看起来像这样:

int foo() {
static int timesCalled = 0;
++timesCalled;
return timesCalled;
}

在 Objective-C 中,基本上是一样的:

- (NSInteger)foo {
static NSInteger timesCalled = 0;
++timesCalled;
return timesCalled;
}

但我在斯威夫特身上做不了这种事。我尝试用以下方法声明这个变量:

static var timesCalledA = 0
var static timesCalledB = 0
var timesCalledC: static Int = 0
var timesCalledD: Int static = 0

但这些都会导致错误。

  • 第一个抱怨“静态属性只能在类型上声明”。
  • 第二个包含“ Expected Declaration”(其中有 static)和“ Expected pattern”(其中有 timesCalledB)
  • 第三个语句抱怨“行上的连续语句必须用’;’分隔”(在冒号和 static之间的空格)和“期望类型”(在 static所在的位置)
  • 第四个声明抱怨“行上的连续语句必须用’;’分隔”(在 Intstatic之间的空格中)和“期望声明”(在等号下)
64283 次浏览

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

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

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

“static” methods and properties are now allowed in classes (as an alias for “class final”). You are now allowed to declare static stored properties in classes, which have global storage and are lazily initialized on first access (like global variables). Protocols now declare type requirements as “static” requirements instead of declaring them as “class” requirements. (17198298)

It appears that functions cannot contain static declarations (as asked in question). Instead, the declaration must be done at the class level.

Simple example showing a static property incremented inside a class (aka static) function, although a 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

Another solution

class Myclass {
static var timesCalled = 0
func foo() -> Int {
Myclass.timesCalled += 1
return Myclass.timesCalled
}
}