Creating and intialising

A new instance of a class is created by calling the class name like a function:

var peter = Person()

At the moment, the Person class is not very useful so let’s add some functionality to it. A Person should have a name and an age. These values will be stored internally in properties on the Person instance called name and age. Since every person needs these attributes, we want to make sure we specify them at the time of creation of the Person instance. We do this with a special init() method. The init() method is optional.

class Person {
    init(name, age) { = name
        self.age = age

Now we can create people like this:

var peter = Person("Peter", 17)
var tony = Person("Tony", 40)

# Print out some instance values.
print(peter.age) # => 17
print( # => "Tony"

# We can alter the existing properties: = "Anthony"
print( # => "Anthony"