Start learning free

LESSON 183 OF 349 · OBJECT-ORIENTED PROGRAMMING

Constructors in Swift in Swift

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object. It's used to set up the object's initial state.


  • In Swift, a constructor is called an initializer and is defined using init:

    class Dog {
        var name: String
        var age: Int
    
        init(name: String, age: Int) {
            self.name = name
            self.age = age
        }
    }
    

  • Then create objects with arguments: Dog(name: "Rex", age: 4) — the initializer fills in the fields for you.



Full lesson:

In the previous lesson you set fields after creating the object:

var dog = Dog()
dog.name = "Rex"
dog.age = 4

That works, but it's noisy and easy to forget. Initializers let you initialize the fields the moment Dog(...) is called.


Defining an initializer

A Swift initializer has these features:

  • It is always named init (not the class name).

  • It has no return type.

init(name: String, age: Int) {
    self.name = name
    self.age = age
}

The self keyword

The parameter name and the field name have the same identifier. Without self, both sides of name = name would refer to the parameter (the local one wins). self is a built-in reference to "the current object", so self.name is the field, and bare name is the parameter.


Calling the initializer

let rex  = Dog(name: "Rex", age: 4)
let luna = Dog(name: "Luna", age: 7)

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.


The default initializer

If you don't write any initializer, Swift requires all stored properties to be set before using an object — either through a custom init or by giving them default values. The moment you define your own initializer, you must call Dog with the arguments you specified.


Your task

The Dog class already has the name and age fields. Add an initializer that takes name: String and age: Int and assigns them using self. Then in the main code, create two dogs:

let rex  = Dog(name: "Rex", age: 4)
let luna = Dog(name: "Luna", age: 7)

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check

    Constructors 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