Useful Built-in Swift Protocols

Swift has a solid group of protocols you can implement in your classes to make stuff happen. The following sections describe them.

The Equatable Protocol

You use Equatable when you want one class to be comparable to another class, using the == operator. For example, if you have two Car classes that you want to compare for equality, you could adopt the Equatable protocol. You have to implement the == function (which can only be written on a global level), as shown here:

class Bear:Equatable {    var name = "Black Bear"    func growl() {        println("Growllll!!!")    }}func == (lhs:Bear, rhs:Bear) -> Bool {    return lhs.name == rhs.name}var bear1 = Bear()bear1.name = "Black Bear" ...

Get Learning Swift™ Programming 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.