SwiftSwift

swift静态变量

2021-12-19  本文已影响0人  一个好笑的人

问题:

swift不支持直接声明静态局部变量

class Foo{
    static func Print(){
        static var x:Int = 0 // Error:Static properties may only be declared on a type
        x+=1;
        print(Box.x)
    }
}
for _ in 1..<10{
    Foo.Print()
}

报错:Static properties may only be declared on a type (只能在类型中声明)-> 那就添加个类型吧

解决方案:

class Foo{
    static func Print(){
        //static var x:Int = 0
        struct Box{
            static var x:Int = 0
        }
        Box.x+=1;
        print(Box.x)
    }
}
for _ in 1..<10{
    Foo.Print()
}

运行结果 :1 2 3 4 5 6 7 8 9

结论:

想在函数体里面使用局部静态变量,需要给变量套上一个struct外壳再声明为static

上一篇下一篇

猜你喜欢

热点阅读