O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 Town struct 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 = 5_422
    var numberOfStoplights = 4

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

printDescription() 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 mainly worked ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required