Static function variables in Swift

前端 未结 4 1593
鱼传尺愫
鱼传尺愫 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:30

    Another solution

    func makeIncrementerClosure() -> () -> Int {
        var timesCalled = 0
        func incrementer() -> Int {
            timesCalled += 1
            return timesCalled
        }
        return incrementer
    }
    
    let foo = makeIncrementerClosure()
    foo()  // returns 1
    foo()  // returns 2
    

提交回复
热议问题