iOS Developer Library — Pre-Release

Developer

Swift Standard Library Reference

PDF

Equatable

The Equatable protocol makes it possible to determine whether two values of the same type are considered to be equal using the == and != operators.

The Swift standard library provides an implementation for the != operator. As a result, types that conform to the Equatable protocol are required to implement the == operator only.

Determining Equality

==

Determines the equality of two values of the same type.

Declaration

  • func ==(lhs: Self, rhs: Self) -> Bool

Discussion

To conform to the protocol, you must provide an implementation for == at global scope. You should return true if the provided values are equal, otherwise false.

It is up to you to determine what equality means for two values of the conforming type:

  • struct MyStruct: Equatable {
  • var name = "Untitled"
  • }
  • func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
  • return lhs.name == rhs.name
  • }
  • let value1 = MyStruct()
  • var value2 = MyStruct()
  • let firstCheck = value1 == value2
  • // firstCheck is true
  • value2.name = "A New Name"
  • let secondCheck = value1 == value2
  • // secondCheck is false