Swift中的静态函数变量 [英] Static function variables in Swift
本文介绍了Swift中的静态函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C语言中,这可能看起来像这样:
int foo(){
static int timesCalled = 0;
++ timesCalled;
返回timesCalled;
}
在Objective-C中,它基本上是相同的:
- (NSInteger)foo {
static NSInteger timesCalled = 0;
++ timesCalled;
返回timesCalled;
}
但我似乎无法在Swift中做这样的事情。我试过用以下方法声明变量:
static var timesCalledA = 0
var static timesCalledB = 0
var timeCalledC:static Int = 0
var timesCalledD:Int static = 0
但这些都会导致错误。
- 第一种抱怨:静态属性只能在类型上声明。 b $ b
- 第二个抱怨Expected declaration(其中
static
is)和Expected pattern(其中timesCalledB
is) - 第三种抱怨:一行中的连续语句必须用';'分开(在冒号和
static
)和Expected Type(其中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
I'm trying to figure out how to declare a static variable scoped only locally to a function in Swift.
In C, this might look something like this:
int foo() {
static int timesCalled = 0;
++timesCalled;
return timesCalled;
}
In Objective-C, it's basically the same:
- (NSInteger)foo {
static NSInteger timesCalled = 0;
++timesCalled;
return timesCalled;
}
But I can't seem to do anything like this in Swift. I've tried declaring the variable in the following ways:
static var timesCalledA = 0
var static timesCalledB = 0
var timesCalledC: static Int = 0
var timesCalledD: Int static = 0
But these all result in errors.
- The first complains "Static properties may only be declared on a type".
- The second complains "Expected declaration" (where
static
is) and "Expected pattern" (wheretimesCalledB
is) - The third complains "Consecutive statements on a line must be separated by ';'" (in the space between the colon and
static
) and "Expected Type" (wherestatic
is) - The fourth complains "Consecutive statements on a line must be separated by ';'" (in the space between
Int
andstatic
) and "Expected declaration" (under the equals sign)
解决方案
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
这篇关于Swift中的静态函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文