Start learning free

LESSON 182 OF 349 · OBJECT-ORIENTED PROGRAMMING

Creating Objects in Swift in Swift

Lesson

TL ; DR:

  • An object is an instance of a class — a real, usable copy made from the blueprint.


  • You create one by calling the class name like a function:

    let rex = Dog()
    

  • Each call creates a separate object, even if they all come from the same class.



Full lesson:

In the previous lesson you defined the Dog class — the blueprint. But a blueprint isn't a dog. To get an actual dog you can interact with, you need to create an instance of the class. An instance is also called an object.


Creating a new object

To create a new object in Swift, call the class name like a function — this invokes the class's initializer:

let rex = Dog()

What this line does:

  • Dog() calls the initializer and creates a fresh Dog instance.

  • let rex declares a constant named rex that holds a reference to that object.

  • The = connects the two — rex now refers to the freshly-created dog.


Many objects from one class

You can call Dog() as many times as you want, and each call gives you a brand-new, independent object:

let rex   = Dog()
let buddy = Dog()
let luna  = Dog()

rex, buddy, and luna are all Dog objects, but they're different objects. Changing one won't affect the others — they share the blueprint but live their own lives.


Your task

The Dog class is already defined for you. Inside mainFunction, create three separate Dog objects named rex, buddy, and luna. The pre-filled print will confirm:

Created 3 Dog objects
STEP 1 OF 3
    Ctrl + Enter to check

    Creating Objects 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