Conforming to a protocol
You may have noticed some unfamiliar parts to the Int definition from the Swift standard library above. The types SignedInteger, Comparable, and Equatable appear
right after the declaration of Int.
public struct Int : SignedInteger, Comparable, Equatable {
// …
}
These types are known as protocols. By putting them after a semicolon when Int is declared, you are declaring that Int conforms to these protocols.
Protocols contain a set of requirements that conforming types must satisfy. A simple example from the standard library is CustomStringConvertible:
public protocol CustomStringConvertible {
/// A textual representation of this instance. public var description: String { get }
}
This protocol contains one property requirement: description. This description is documented as “A textual representation of this instance.”
If you were to modify DeliveryArea to conform to CustomStringConvertible, you would be required to add a description property with a “textual representation” of the instance. Try this now. Change DeliveryArea to:
struct DeliveryArea: CustomStringConvertible { var range: Double
let center: Location
var description: String {
return "Area with range: (range),
location: x: (center.x) - y: (center.y)"
}
func contains(_ location: Location) -> Bool { let distanceFromCenter =
distance(from: (center.x, center.y),
to: (location.x, location.y))
return distanceFromCenter < range
}
}
The value of the description property is based on the center and current range. This is made possible by implementing it as a computed property. You’ll learn all about computed properties — and more — in the next chapter!
So what exactly does conforming to a protocol do? Because any type conforming to CustomStringConvertible must define description, you can call description on any instance of any type that conforms to CustomStringConvertible. The Swift library takes advantage of this with the print() function. This function will print description to the console instead of a rather noisy default description:
print(area1) // "Area with range: 4.0, location: x: 2.0 - y: 4.0"
print(area2) // "Area with range: 2.5, location: x: 2.0 - y: 4.0"
Conforming your structs to a protocol can help extend the behavior of your named types, in particular with protocols defined in the Swift standard library. In Chapter 17, “Protocols”, you will learn all about defining, using and conforming to protocols as well as using them with the Swift library.