Static function variables in Swift

前端 未结 4 1594
鱼传尺愫
鱼传尺愫 2020-12-02 07:03

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         


        
4条回答
  •  抹茶落季
    2020-12-02 07:25

    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
    

提交回复
热议问题