我试图找出如何声明一个静态变量只有本地的一个函数在Swift中。
在C中,这可能看起来像这样:
int foo() {
static int timesCalled = 0;
++timesCalled;
return timesCalled;
}
在Objective-C中,它基本上是一样的:
- (NSInteger)foo {
static NSInteger timesCalled = 0;
++timesCalled;
return timesCalled;
}
但我似乎不能在Swift中做这样的事情。我已经尝试声明变量在以下方式:
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是)
>第四个提示“在一行上的连续语句必须由’;’”(在Int和static之间的空格中)和“Expected declaration”(在等号下)
我不认为Swift支持静态变量,而没有它附加到一个类/结构。尝试声明一个带有静态变量的私有结构体。
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