我试图弄清楚如何在 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
is)
- 第三个抱怨“一行中的连续语句必须用‘;’分隔”(在冒号和
static
)和“预期类型”(其中static
is)
- 第四个抱怨“一行中的连续语句必须用‘;’分隔”(在
Int
and static
) 和“预期声明”(等号下)
我认为 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)