nhg*_*rif 92 static function swift
我试图弄清楚如何声明一个静态变量,只在本地作用于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)和"预期声明"(等号下签)Bry*_*hen 146
我不认为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
mon*_*dis 22
另一种方法
func makeIncrementerClosure() -> () -> Int {
    var timesCalled = 0
    func incrementer() -> Int {
        timesCalled += 1
        return timesCalled
    }
    return incrementer
}
let foo = makeIncrementerClosure()
foo()  // returns 1
foo()  // returns 2
Dan*_*iel 18
带有Xcode 6.3的Swift 1.2现在支持静态.从Xcode 6.3 beta版发行说明:
现在允许在类中使用"静态"方法和属性(作为"类final"的别名).现在,您可以在类中声明静态存储属性,这些属性具有全局存储,并且在首次访问时(例如全局变量)会被懒惰地初始化.协议现在将类型要求声明为"静态"要求,而不是将它们声明为"类"要求.(17198298)
似乎函数不能包含静态声明(如所讨论的那样).相反,声明必须在类级别完成.
虽然不需要类函数,但显示静态属性在类(也称为静态)函数内递增的简单示例:
class StaticThing
{
    static var timesCalled = 0
    class func doSomething()
    {
        timesCalled++
        println(timesCalled)
    }
}
StaticThing.doSomething()
StaticThing.doSomething()
StaticThing.doSomething()
输出:
1
2
3