Start learning free

LESSON 205 OF 415 · FUNCTIONS & CLASSES

Defining a Class in Swift

Lesson Read the full explanation

TL ; DR:

  • A class is a blueprint for creating objects. It groups together related data and behavior under a single name.


  • In Swift, you define a class with the class keyword, followed by the class name and a pair of curly braces:

    class Dog {
    
    }
    

    The body of the class can be empty — that's still a valid class. We'll add data and behavior to it in the next lessons.



Full lesson:

So far, you've worked with built-in types like Int, String, and arrays. But what if you want to model something the language doesn't have a type for — like a Dog, a BankAccount, or a Game?

That's what classes are for. A class lets you define your own type by listing what data it holds and what actions it can perform.


Why classes?

Imagine you're writing a program about dogs. Each dog has a name, an age, and can bark. Without classes, you'd have to track each dog's name in one variable, age in another, and write a separate bark() function for each. That gets messy fast.

With a class, you bundle all of that into one neat package called Dog:

class Dog {
    // We'll add fields (data) and methods (behavior) here in upcoming lessons.
}

The syntax

Defining an empty class in Swift looks like this:

class ClassName {
}

Three things to notice:

  • The keyword class tells Swift you're defining a new type.

  • ClassName is the name you choose. By convention, Swift class names use PascalCase — capitalized words with no underscores: Dog, BankAccount, HighScore.

  • The curly braces { } hold the body of the class. They can be empty for now.


Your task

Define an empty class called Dog. The pre-filled code in mainFunction will create an instance of your class and print a confirmation message. If you define the class correctly, the program will compile and print:

Defined the Dog class!
STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · FUNCTIONS & CLASSES

    Defining A Class in Swift, explained

    What a class is

    A class is a blueprint for your own type. Swift ships with types such as Int, String and Array, but a program about dogs, bank accounts or games needs types that describe those things. A class lets you group the data a thing has and the actions it can perform under one name. Objects made from the class are the actual dogs, accounts or games; the class is the description they follow.

    The syntax

    The smallest class in Swift has a keyword, a name and a pair of braces:

    class Dog {
    }
    
    • class tells the compiler a new type is being declared.
    • Dog is the name. Swift convention is PascalCase: Dog, BankAccount, HighScore. Type names start with a capital letter, while variables and functions start lowercase.
    • The braces hold the body, which is where properties and methods go. An empty body is valid.

    Unlike some languages, Swift needs no semicolon after the closing brace, and the file doesn't have to be named after the class.

    Using the class

    Once Dog exists, you can create a value of that type by calling it like a function:

    let rex = Dog()
    let luna = Dog()
    print(rex === luna)    // false
    print(type(of: rex))   // Dog
    

    This prints false and then Dog. The operator === asks whether two constants refer to the very same object; each call to Dog() creates a new one, so the answer is false. Creating objects is the topic of the next lesson.

    The call Dog() works with an empty body because a class that has no stored properties gets a default initializer from the compiler. You don't write it.

    The exercise

    The starter code already contains a Solution class whose mainFunction writes let dog = Dog() and then prints a message. Until Dog exists, that line can't compile. The task is to declare an empty Dog class above Solution:

    class Dog {
    }
    
    class Solution {
        func mainFunction() {
            let dog = Dog()
            print("Defined the Dog class!")
        }
    }
    

    With that in place the program compiles and mainFunction prints Defined the Dog class!. The compiler also warns that the constant dog is never used; it's only a warning, and the program still runs.

    Where a class definition goes

    Classes are normally declared at the top level of a file, next to other classes and functions. The lesson places Dog first because that reads naturally, with the blueprint before the code that builds from it.

    A class is also a type name you can use anywhere a type is expected. For example, var pet: Dog? declares a variable that may hold a dog, and func adopt(_ dog: Dog) declares a function that takes one. That is the real payoff of defining the class: your own concept becomes something the rest of the program can name and pass around.

    Common mistakes

    • Lowercase name. class dog compiles, but breaks the convention, and the starter code refers to Dog. Swift is case-sensitive, so dog and Dog are different names.
    • Declaring the class inside mainFunction. That is legal Swift, but the type would exist only in that function. Put it at the top level, as the lesson shows.
    • Missing braces. class Dog on its own is a syntax error; the braces are required even when they are empty.

    Key takeaways

    • A class is a blueprint for a new type, declared with class Name { }.
    • Class names use PascalCase.
    • An empty class is valid and can be created with Dog().
    • Fields and methods, added in the following lessons, go between the braces.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free