DevPrep

All topics › The Swift Language

static or the class modifier?

Junior PRO

The idea

Both keywords declare a member of the type, not of an instance. The difference is overriding:

Inside a class static is equivalent to final class.

class Shape {
    static let kind = "shape"             // cannot be overridden
    class var name: String { "Shape" }    // can be overridden
    static func make() -> Shape { Shape() }
    // class var stored = 0   // error: class stored properties not supported
}
class Circle: Shape {
    override class var name: String { "Circle" }
    // override static func make() — error: cannot override static method
}
struct Point {
    static let zero = Point(x: 0, y: 0)   // struct/enum: static only
    var x, y: Double
}
print(Circle.name, Shape.name, Shape.kind)   // Circle Shape shape

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store