Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. SwiftBeginner - About Classes and Instances

About Classes and Instances - Images: Japanese

Hey there, everyone!

This is article 30 of the Swift Beginner's Course. If you've been following along from the start, great work making it this far! And if this is your first time here, feel free to settle in and take it at your own pace.

Alright, today we're tackling one of the most important topics: 'classes' and 'instances'.

We'll cover how to use classes and what the concepts are all about in a later article, so let's start by looking at the syntax first. Here's a quick sample to kick things off.

class Test {

}

Here we've defined a class called 'Test'. To define a class, you write 'class', followed by a space and then an identifier (name) of your choice. After that, you add '{}' and write whatever you want inside it.

In more generic terms, it looks like this.

class ClassName {
    // code goes here...
}

That's all there is to defining a class. Pretty straightforward so far, right?

One quick note on naming: it's a good idea to use UpperCamelCase for your class identifiers, where the first letter is capitalized.

For example, if you wanted a class to mean "test of class", you'd write it as 'TestOfClass'.

Depending on the language or the coding conventions at your workplace, things may differ — but in Swift, writing class names in UpperCamelCase is the accepted convention.

Now, the sample above has an empty body and doesn't do anything useful, so let's add some code inside it. We'll start by adding a constant 'n'.

class Test {
    let n = 1
}

Let's go ahead and add a variable and a function too.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

Now we have a class with actual content inside it.

So now we want to run the code inside this class — but here's something important to be aware of.

Think of a class as a kind of "blueprint" that bundles together constants, variables, functions, and other code.

Let's take a step back and think about functions. With a function, the flow was simple: "define the function, then call it wherever you need it."

func test() { // Define the function.
    print("Hatsune Miku")
}

test() // Call it.

With a class, though, it's just a blueprint — so when you define a class, there's no actual object in existence yet.

In order to run the code inside it, you need to create a concrete object based on that blueprint. This is what's called an 'instance'. Here's how you create one.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

Test() // Creates an object based on class 'Test'. This is the 'instance'.

Take a look at 'Test()' above. Writing 'ClassName()' like this creates an instance. It looks similar to calling a function, doesn't it?

Now let's try accessing the contents of that instance. The example below outputs the constant 'n' from class 'Test'.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

print(Test().n) // Creates an instance from class 'Test' and outputs the value of constant 'n', which is '1'.

Notice Test().n above. You use '.' like this — instance.identifier — to access the data inside an instance.

And to call the function f inside class Test, it would look like this.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

Test().f() // Creates an instance from class 'Test' and calls the function 'f' inside it.

You write instance.functionName() — just like Test().f(). The key part is the () at the end, which is what actually triggers the function call.

So we've managed to create an instance from a class and access or run the code inside it.

There's one thing worth keeping in mind here: due to the nature of classes, doing things like 'Test().n' or 'Test().f()' — where you create an instance and immediately do something with it — is not commonly done in practice.

The typical approach is to store the created instance in a variable or constant first, and then use it from there. Like this.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

let testA = Test() // Assign the instance to a constant first.

print(testA.n) // Use constant 'testA' to do things.
testA.f() // Use constant 'testA' to do things.

There are situations where creating an instance and immediately doing something with it is the right call, so it's not a hard rule — but in general, assigning it to a variable or constant first is the standard approach.

Doing okay so far? It can feel a bit tricky, so here's a quick comparison of the flow when using a function versus a class.

With a function:

  1. Define the function.
  2. Call that function.

With a class:

  1. Define the class.
  2. Create an instance from that class.
  3. Use the instance to run your code.

Compared to functions, classes involve quite a few more steps.

One thing that's easy to trip up on: when you actually run code, you use the 'instance' — not the class definition itself. Keep that in mind.

Let's also go over some terminology.

Variables, constants, and functions written inside a class are collectively called 'properties'. And functions defined inside a class are specifically called 'methods'.

One thing to note: the terms property and method can vary depending on the language or the person using them.

For example, in JavaScript, a function inside an object is called a 'method', and in Java, a variable defined inside a class is called a 'member variable'.

That said, they generally refer to the same kinds of things, so calling a function a method or referring to a variable defined inside a class simply as a variable is totally fine in most cases. (Apologies if that turns out not to be the case somewhere!)

On this site, using terms like 'property' can sometimes make things harder to follow, so explanations will generally say things like "the variable inside the class." Just a heads-up on that.

Finally, let's also confirm that you can overwrite the properties of an instance. Take a look at this sample.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

let testA = Test() // Create an instance.

Class 'Test' contains the constant 'n' and the variable '_n'. Variable properties can be overwritten — constants cannot. Here's how that looks.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

let testA = Test() // Create an instance and assign it to constant 'testA'.

testA._n = 10 // Overwrite the variable '_n' inside the instance.

testA.f() // Outputs '1' and '10'.

testA.n = 10 // Constants cannot be overwritten. This is an error.

Note that you're modifying the instance, not the class itself. This is an easy thing to mix up, so watch out for it.

One more thing to note. Take a look at 'testA', which holds the instance. It's declared with 'let'. You might expect that to prevent you from modifying its properties — but properties can actually still be changed.

It's a bit confusing, but what 'let' does here is prevent the instance itself from being reassigned. Here's an example.

class Test {
    let n = 1
    var _n = 2

    func f(){
        print(n)
        print(_n)
    }
}

var testA = Test() // Assign an instance to 'testA', declared with 'var'.

testA._n = 10 // Overwrite the variable '_n' inside the instance.

testA.f() // Outputs '1' and '10'.

testA = Test() // Reassign a new instance to 'testA'. This is fine since it was declared with 'var'.

testA.f() // A fresh instance was created, so it outputs '1' and '2'.

let testB = Test() // Assign an instance to 'testB', declared with 'let'.

testB = Test() // Declared with 'let', so reassignment is not allowed.

It gets a bit complicated, so just be careful not to mix things up.

That covers the basics of classes and instances for now.

In the next article, we'll look at initializers. The explanation of how to use classes and the concepts behind them comes after that, so don't worry about it for now and just keep moving forward.

That's all for this one. See you in the next article!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .