Start learning free

LESSON 402 OF 415 · OBJECT-ORIENTED PROGRAMMING

Static Members in Swift in Swift

Practice

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

    Static Members in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free