Start learning free

LESSON 29 OF 71 · OBJECT-ORIENTED PROGRAMMING

Static Members in Swift: static var and Counting Instances

Practice Read the full explanation

TL;DR:

A static property is declared with the static keyword. It belongs to the type itself, so there is one copy shared by every Dog, and you reach it through the type name: Dog.count, not through an object. static func works the same way for methods.

You start with:

class Dog {
    let name: String
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Add static var count = 0 inside Dog.
  • Write the initializer init(_ name: String): assign self.name = name, then Dog.count += 1.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.count.

class Dog {
    static var count = 0
    let name: String

    init(_ name: String) {
        self.name = name
        Dog.count += 1
    }
}

class Solution {
    func mainFunction() {
        let rex = Dog("Rex")
        let buddy = Dog("Buddy")
        _ = rex
        _ = buddy
        print(Dog.count)
        let third = Dog("Max")
        print(Dog.count)
        print(third.name)
        _ = Dog("Luna")
        print(Dog.count)
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · OBJECT-ORIENTED PROGRAMMING

    Static Members in Swift, explained

    Problem overview

    The lesson starts with a Dog class that has a name and nothing else. The task is to count how many Dog objects have been created, using one counter shared by all of them. You add a static var count = 0 to Dog, and an initializer init(_ name: String) that stores the name and then adds 1 to Dog.count.

    The program already in the editor creates Rex and Buddy and prints the counter, creates Max and prints the counter and Max's name, and creates Luna and prints the counter once more. Those lines stay as they are. The expected output is:

    2
    3
    Max
    4

    Approach: store the counter on the type, not on each dog

    An ordinary property such as name belongs to one object: every Dog has its own. A counter of dogs can't live there, because each dog would hold its own separate count. The count describes all dogs together, so it should exist once, attached to the type Dog itself.

    In Swift that is a static property, declared with the static keyword. There is exactly one copy, and you reach it through the type name: Dog.count. Since every initializer call creates one dog, the initializer is the natural place to add 1.

    A static stored property is created the first time it is used, not when an object is made, and it lives for the whole run of the program. That is why Dog.count is already 0 before any dog exists. A property like name belongs to each object; a static property belongs to the type.

    Static properties are not only for counters. Any value that is the same for every object of a type, or that describes the type as a whole, fits: a shared configuration value, the number of objects created so far, or a constant such as a maximum size. The question to ask is always whether the value belongs to one object or to all of them.

    Step by step

    1. Declare static var count = 0 inside Dog. The initial value 0 means no dog exists before any init has run. It is a var because it changes.
    2. Start the initializer, init(_ name: String). The underscore removes the argument label, so callers write Dog("Rex") rather than Dog(name: "Rex"). The initializer runs once for every new dog.
    3. Store the parameter in self.name. The parameter and the property share the name name, so self.name is the property and the bare name is the parameter. A let property must be assigned in the initializer: leaving it out fails with return from initializer without initializing all stored properties.
    4. Add 1 with Dog.count += 1. Every new dog is counted, whatever its name.

    The solution in Swift

    class Dog {
        static var count = 0
        let name: String
    
        init(_ name: String) {
            self.name = name
            Dog.count += 1
        }
    }
    
    class Solution {
        func mainFunction() {
            let rex = Dog("Rex")
            let buddy = Dog("Buddy")
            _ = rex
            _ = buddy
            print(Dog.count)
            let third = Dog("Max")
            print(Dog.count)
            print(third.name)
            _ = Dog("Luna")
            print(Dog.count)
        }
    }
    

    Calling mainFunction() on a Solution prints:

    2
    3
    Max
    4

    The Swift details worth a closer look:

    • The counter is reached through the type. Dog.count works anywhere, with or without a dog in hand. An instance can't read it. Writing d.count for a Dog named d is a compile error: static member 'count' cannot be used on instance of type 'Dog'.
    • Inside init the type name is needed. Writing just count += 1 in the initializer fails with the same message, because an initializer works on an instance. Spell out Dog.count.
    • One copy. Every dog shares the one counter. Setting Dog.count = 10 from outside and then creating a dog makes it 11. That is also the weakness of a public counter: any code can change it.
    • The wrong version: a plain var count = 0. Without static, each dog gets its own count starting at 0, and the initializer raises it to 1. After creating two dogs, each one's count is 1, and the type has no total.
    • The _ = rex lines. Assigning to _ says "I'm deliberately ignoring this value". It keeps the compiler from warning that rex and buddy are never used. _ = Dog("Luna") creates a dog and discards it, and the counter still goes up, because counting happens in init.
    • static func. Methods work the same way: a static func belongs to the type and is called as Dog.describe(). Inside a static method, count without the prefix means the static property. A method like static func describe() -> String { return "dogs: \(count)" } returns "dogs: 1" after one dog is created.

    Edge cases and common mistakes

    • Counting in the wrong place. The counter belongs in the initializer, not in mainFunction. Every code path that creates a Dog then counts it, and the count can't drift.
    • Forgetting static. A per-object counter prints 1 for every dog and never reaches 2.
    • Using count without Dog. in init. The compiler rejects it, as shown above.
    • Using let for the counter. A static let can't change, so Dog.count += 1 fails with left side of mutating operator isn't mutable.
    • Creating dogs you don't keep. Dogs created and thrown away are still counted. Dog("Luna") with no variable counts as the fourth dog.
    • The label. Without the _ in init(_ name: String), the call Dog("Rex") fails with missing argument label 'name:', because the label would be required.

    Testing

    • Running the lesson's program prints 2, 3, Max, 4, one per line.
    • Before any dog exists, Dog.count is 0.
    • Creating one more dog after the program raises the counter by exactly 1, whatever its name.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free