Menu
Coddy logo textTech

Static Members

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 14 of 57.

A static property belongs to the type itself, not to any instance. There is exactly one copy, read through the type name:

struct Temperature {
    static let freezing = 0.0
    static let boiling = 100.0
    var celsius: Double
}

print(Temperature.boiling - Temperature.freezing)

Output:

100.0

A static var can change, which makes it useful for data shared by all instances, such as a counter of how many were created:

class Ticket {
    static var issued = 0
    let number: Int

    init() {
        Ticket.issued += 1
        number = Ticket.issued
    }
}

let a = Ticket()
let b = Ticket()
print(a.number)
print(b.number)
print(Ticket.issued)

Output:

1
2
2

A static func is called on the type. It has no self instance to work with, so it only uses its arguments and other static members. It is a good home for helpers and for named ways to build instances:

struct Color {
    var red: Int
    var green: Int
    var blue: Int

    static func gray(_ level: Int) -> Color {
        Color(red: level, green: level, blue: level)
    }
}

let c = Color.gray(128)
print(c.red + c.green + c.blue)

Output:

384

Inside the type, Self is another way to name the type, so static members can be written as Self.issued. Instance methods can read static members, but a static method cannot read instance properties, because it is not called on an instance.

struct Level {
    static let maximum = 10
    var current = 1
    func isMax() -> Bool { current == Self.maximum }   // instance reads static
    static func describe() -> String { "levels 1-\(maximum)" } // static reads static
}
challenge icon

Challenge

Easy

Complete the class Order. A static property nextId starts at 1, and each new order takes the current nextId as its id and increases it. A static constant taxPercent is 10. The instance method total() returns the subtotal plus the tax (rounded down), and the static method summary(of:) receives an array of orders and returns 3 orders, 660 total.

The supplied code reads one subtotal per line, creates an order for each, prints #1: 110 for each order, and finally prints the summary.

Your code goes in Order.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
var orders: [Order] = []
for line in input {
    let order = Order(subtotal: Int(line)!)
    orders.append(order)
    print("#\(order.id): \(order.total())")
}
print(Order.summary(of: orders))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground