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
- Declare
static var count = 0insideDog. The initial value 0 means no dog exists before anyinithas run. It is avarbecause it changes. - Start the initializer,
init(_ name: String). The underscore removes the argument label, so callers writeDog("Rex")rather thanDog(name: "Rex"). The initializer runs once for every new dog. - Store the parameter in
self.name. The parameter and the property share the namename, soself.nameis the property and the barenameis the parameter. Aletproperty must be assigned in the initializer: leaving it out fails withreturn from initializer without initializing all stored properties. - 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.countworks anywhere, with or without a dog in hand. An instance can't read it. Writingd.countfor aDognameddis a compile error:static member 'count' cannot be used on instance of type 'Dog'. - Inside
initthe type name is needed. Writing justcount += 1in the initializer fails with the same message, because an initializer works on an instance. Spell outDog.count. - One copy. Every dog shares the one counter. Setting
Dog.count = 10from 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. Withoutstatic, each dog gets its owncountstarting at 0, and the initializer raises it to 1. After creating two dogs, each one'scountis 1, and the type has no total. - The
_ = rexlines. Assigning to_says "I'm deliberately ignoring this value". It keeps the compiler from warning thatrexandbuddyare never used._ = Dog("Luna")creates a dog and discards it, and the counter still goes up, because counting happens ininit. static func. Methods work the same way: astatic funcbelongs to the type and is called asDog.describe(). Inside a static method,countwithout the prefix means the static property. A method likestatic 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 aDogthen counts it, and the count can't drift. - Forgetting
static. A per-object counter prints 1 for every dog and never reaches 2. - Using
countwithoutDog.ininit. The compiler rejects it, as shown above. - Using
letfor the counter. Astatic letcan't change, soDog.count += 1fails withleft 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
_ininit(_ name: String), the callDog("Rex")fails withmissing 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.countis0. - Creating one more dog after the program raises the counter by exactly 1, whatever its name.
