Swift中的静态函数变量
发布时间:2020-12-14 06:10:32 所属栏目:百科 来源:网络整理
导读:我试图找出如何声明一个静态变量只有本地的一个函数在Swift中。 在C中,这可能看起来像这样: int foo() { static int timesCalled = 0; ++timesCalled; return timesCalled;} 在Objective-C中,它基本上是一样的: - (NSInteger)foo { static NSInteger tim
我试图找出如何声明一个静态变量只有本地的一个函数在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 但这些都导致错误。 >第一个抱怨“静态属性只能在类型上声明”。
我不认为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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |