Start learning free

LESSON 181 OF 349 · OBJECT-ORIENTED PROGRAMMING

Defining a Class in Swift in Swift

Lesson

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

    Defining A Class in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free