Menu
Coddy logo textTech

Defining Classes

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 2 of 57.

A class describes a kind of object: the data each object holds and what it can do. class Dog { ... } declares the type, and Dog() creates an object of that type, also called an instance:

class Dog {
    var name = "Rex"
    var age = 3
}

let dog = Dog()
print(dog.name)
print(dog.age)

Output:

Rex
3

The variables inside a class are its properties. Every instance has its own copy, read and changed with a dot:

class Dog {
    var name = "Rex"
    var age = 3
}

let first = Dog()
let second = Dog()
second.name = "Bella"
print(first.name)
print(second.name)

Output:

Rex
Bella

A function inside a class is a method. A method can read and change the properties of the instance it is called on:

class Counter {
    var count = 0

    func increment() {
        count += 1
    }

    func report() -> String {
        "count is \(count)"
    }
}

let clicks = Counter()
clicks.increment()
clicks.increment()
print(clicks.report())

Output:

count is 2

Type names are written in UpperCamelCase (BankAccount); properties and methods in lowerCamelCase (balance, deposit()). Putting the data and the functions that work on it into one type is the core idea of object-oriented programming: code that uses a Counter calls increment() and never needs to know how the count is stored.

class BankAccount {
    var balance = 0

    func deposit(_ amount: Int) {
        balance += amount
    }
}
challenge icon

Challenge

Easy

Complete the method describe() of the class Pet. It returns one sentence built from the properties: a pet named Rex, species dog, age 3 gives Rex is a 3 year old dog.

The supplied code creates a Pet, sets its properties from the input (name, species, age) and prints the result of describe().

Your code goes in Pet.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let pet = Pet()
pet.name = input[0]
pet.species = input[1]
pet.age = Int(input[2])!
print(pet.describe())
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground