Equatable Interface
🚧 Status: The
Equatable
interface is not implemented yet.
An equatable type is a type that can be compared for equality. Types are equatable when they implement the Equatable
interface.
Equatable types can be compared for equality using the equals operator (==
) or inequality using the unequals operator (!=
).
Most of the built-in types are equatable, like booleans and integers. Arrays are equatable when their elements are equatable. Dictionaries are equatable when their values are equatable.
To make a type equatable the Equatable
interface must be implemented, which requires the implementation of the function equals
, which accepts another value that the given value should be compared for equality.
struct interface Equatable {
pub fun equals(_ other: {Equatable}): Bool
}
// Declare a struct named `Cat`, which has one field named `id`
// that has type `Int`, i.e., the identifier of the cat.
//
// `Cat` also will implement the interface `Equatable`
// to allow cats to be compared for equality.
//
struct Cat: Equatable {
pub let id: Int
init(id: Int) {
self.id = id
}
pub fun equals(_ other: {Equatable}): Bool {
if let otherCat = other as? Cat {
// Cats are equal if their identifier matches.
//
return otherCat.id == self.id
} else {
return false
}
}
}
Cat(1) == Cat(2) // is `false`
Cat(3) == Cat(3) // is `true`
Last updated
Was this helpful?