Introducing methods

Using some of the capabilities of structs, you could now make a pizza delivery range calculator that looks something like this:

let areas = [

DeliveryArea(range: 2.5, center: Location(x: 2, y: 4)),

DeliveryArea(range: 4.5, center: Location(x: 9, y: 7))

]

func isInDeliveryRange(_ location: Location) -> Bool { for area in areas {

let distanceToStore =

distance(from: (area.center.x, area.center.y), to: (location.x, location.y))

if distanceToStore < area.range { return true

}

}

return false

}

let customerLocation1 = Location(x: 8, y: 1) let customerLocation2 = Location(x: 5, y: 5)

print(isInDeliveryRange(customerLocation1)) // false print(isInDeliveryRange(customerLocation2)) // true

In this example, there’s an array areas and a function that uses that array to determine if a customer’s location is within any of these areas.

The idea of being in range of a restaurant is very tightly coupled to the characteristics of a single pizza restaurant. In fact, all of the calculations in isInDeliveryRange occur on one location at a time. Wouldn’t it be great if DeliveryArea itself could tell you if the restaurant can deliver to a certain location?

Much like a struct can have constants and variables, it can also define its own

functions. Update DeliveryArea to include the following within the curly braces:

func contains(_ location: Location) -> Bool { let distanceFromCenter =

distance(from: (center.x, center.y),

to: (location.x, location.y))

return distanceFromCenter < range

}

This code defines a function contains, which is now a member of DeliveryArea. Functions that are members of types are called methods. Notice how the contains method uses the center and range properties of the current location. This behavior makes methods different from regular functions. You’ll learn more about methods in Chapter 13.

Just like other members of structs, you can use dot syntax to access a method through an instance of its associated type:

let area = DeliveryArea(range: 4.5,

center: Location(x: 5, y: 5)) let customerLocation = Location(x: 2, y: 2) area.contains(customerLocation) // true

results matching ""

    No results matching ""