Start learning free

LESSON 288 OF 678 · FUNCTIONS & CLASSES

Constructors 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 every stored property has a default value (as in the previous lesson), Swift gives the class a default initializer, Dog(). If a property has no default value, you must write an init that sets it. The moment you define your own initializer, Dog() is no longer available: 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