Swift Introduction | Class Basics | Using Classes

To use a class, you need to create an instance from it and understand how to access the properties and methods in that instance.

Creating an Instance

To create an instance from a class, call the class name like a function. For example, if you have a class named Abc, create an instance as follows.

var obj:Abc = Abc();

Usually, you do not specify any arguments. You can pass arguments when creating an instance, which will be explained later. Calling the class name like a function creates an instance.

Accessing Properties and Methods

To access a property or call a method, write a dot (.) after the variable that holds the instance. If class Abc has a property named efg and a method named xyz, use them as follows.

var obj:Abc = Abc();
var x = obj.efg; // retrieve the value of efg
obj.efg = 〇〇; // change the value of efg
obj.xyz(); // call xyz

The following example uses the Helo class introduced previously.

import Cocoa

class Helo {
    var name = "Taro";

    func say(){
        print("Hello, " + name + "!");
    }
}

var obj:Helo = Helo();
obj.say();

obj.name = "Hanako";
obj.say();

This code creates a Helo instance and displays a message with its say method. It then changes the instance’s name property and calls say again.

When an instance is created, it receives the contents defined by the class. If you create multiple instances, each one stores its properties independently. In this example, each instance can have a different name, so the message displayed by say can differ for each instance.