【发布时间】:2014-10-10 20:51:46
【问题描述】:
我正在试图弄清楚如何在 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
但这些都会导致错误。
- 第一个抱怨“静态属性只能在一个类型上声明”。
- 第二个抱怨“预期声明”(
static是)和“预期模式”(timesCalledB是) - 第三个抱怨“一行上的连续语句必须用';'分隔”(在冒号和
static之间的空格中)和“预期类型”(static是) - 第四个抱怨“一行上的连续语句必须用';'分隔”(在
Int和static之间的空格中)和“预期声明”(在等号下)
【问题讨论】: