我正在尝试弄清楚如何在 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
之间的空格)和“预期声明”(在等号)
最佳答案
我认为 Swift 不支持没有附加到类/结构的静态变量。尝试用静态变量声明一个私有(private)结构。
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
关于function - Swift 中的静态函数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25354882/