Instance Methods

The print() function above is a fine way to print a description of myTown. But a town should know how to describe itself. Create a function on the struct Town that prints the values of its properties to the console. Navigate to your Town.swift file and add the following function definition.

Listing 15.5  Letting Town describe itself (Town.swift)

struct Town {
    var population = 5422
    var numberOfStoplights = 4

    func printTownDescription() {
        print("Population: \(population);
               number of stoplights: \(numberOfStoplights)")
    }
}

printTownDescription() is a method because it is a function that is associated with a particular type. (Recall from Chapter 14 that this is the definition of a method.) Thus far, you have ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.