Swift Introduction | Class Basics | Defining Classes

Swift is an object-oriented language, which means that it supports objects.

Swift generally uses class-based object orientation. A class defines a blueprint for objects, and objects are created from that blueprint.

An object created from a class is called an instance. In Swift, you define a class and create instances from it to perform actual work.

A class can contain variables that store values and functions that perform processing. Variables provided by a class are called properties, and functions provided by a class are called methods.

Defining a Class

The simplest form of a class definition is as follows.

class ClassName {
    ... write properties and methods ...
}

Write class ClassName, followed by braces ({}). Define the class’s properties and methods inside the braces.

The following example defines a class named Helo.

import Cocoa

class Helo {
    var name = "Taro";

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

This class has a property named name and a method named say. These are the features provided by the Helo class.

The say method uses the name property. A method in a class can directly use the properties and methods defined by that class.

Assistant Editor

This example uses println, a function that sends a value to standard output. When running code in an Xcode playground, it is convenient to display the Assistant Editor.

From Xcode’s View menu, select Assistant Editor > Show Assistant Editor. A new area appears on the right side of the screen. When println runs, a Console Output item automatically appears there and displays the result.