Lesson 14 of 15

Classes

Classes

Classes are reference types (unlike structs which are value types). Multiple variables can refer to the same instance:

class Animal {
    var name: String

    init(_ name: String) {
        self.name = name
    }

    func speak() -> String {
        return "..."
    }
}

let a = Animal("Dog")
print(a.speak())  // ...

Inheritance

class Dog: Animal {
    override func speak() -> String {
        return "Woof!"
    }
}

let d = Dog("Rex")
print(d.speak())  // Woof!

Your Task

Create a Counter class with:

  • A stored property count initialized to 0
  • An increment() method that adds 1 to count
  • A value() method that returns the current count
JS Transpiler loading...
Loading...
Click "Run" to execute your code.