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 = 0insideDog. - Write the initializer
init(_ name: String): assignself.name = name, thenDog.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
RexandBuddyand prints the counter; then it createsMax, prints the counter and Max's name, createsLuna, 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)
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
