Does swift have class level static variables? [dup

2020-02-18 02:54发布

How to declare static constant in class scope? such as

class let Constant: Double = 3.1415926
// I know that in class we use class modifier instead of static.

1条回答
走好不送
2楼-- · 2020-02-18 03:50

Swift supports static type properties, including on classes, as of Swift 1.2:

class MyClass {
    static let pi = 3.1415926
}

If you need to have a class variable that is overridable in a subclass, you'll need to use a computed class property:

class MyClass {
    class var pi: Double { return 3.1415926 }
}

class IndianaClass : MyClass {
    override class var pi: Double { return 4 / (5 / 4) }
}
查看更多
登录 后发表回答