Swift: Operators, methods and algorithms that work with types that adopt the Equatable protocol


It might seem rather intuitive that we can compare numbers, strings and type instances, but it is good to begin looking at the syntax of these comparisons so that we can see our whole range of options. And also because if we can grasp the concept of generics and protocols on the simplest examples, then we can transfer this knowledge to the more complex cases.
func !=<KeyType : Equatable, ValueType : Equatable>(lhs: [KeyType : ValueType], rhs: [KeyType : ValueType]) -> Bool

/// Returns true if the arrays do not contain the same elements.
func !=<T : Equatable>(lhs: [T], rhs: [T]) -> Bool

/// Returns true if the arrays do not contain the same elements.
func !=<T : Equatable>(lhs: Slice<T>, rhs: Slice<T>) -> Bool

/// Returns true if the arrays do not contain the same elements.
func !=<T : Equatable>(lhs: ContiguousArray<T>, rhs: ContiguousArray<T>) -> Bool

func !=<T : Equatable>(lhs: T?, rhs: T?) -> Bool
func !=<T : Equatable>(lhs: T, rhs: T) -> Bool

/// Returns true if these arrays contain the same elements.
func ==<T : Equatable>(lhs: ContiguousArray<T>, rhs: ContiguousArray<T>) -> Bool

/// Returns true if these arrays contain the same elements.
func ==<T : Equatable>(lhs: Slice<T>, rhs: Slice<T>) -> Bool

/// Returns true if these arrays contain the same elements.
func ==<T : Equatable>(lhs: [T], rhs: [T]) -> Bool
func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool
func ==<KeyType : Equatable, ValueType : Equatable>(lhs: [KeyType : ValueType], rhs: [KeyType : ValueType]) -> Bool

/// Return `true` iff `x` is in `seq`.
func contains<S : Sequence where S.GeneratorType.Element : Equatable>(seq: S, x: S.GeneratorType.Element) -> Bool

/// Return true iff `a1` and `a2` contain the same elements.
func equal<S1 : Sequence, S2 : Sequence where S1.GeneratorType.Element == S1.GeneratorType.Element, S1.GeneratorType.Element : Equatable>(a1: S1, a2: S2) -> Bool

func find<C : Collection where C.GeneratorType.Element : Equatable>(domain: C, value: C.GeneratorType.Element) -> C.IndexType?

/// Return true iff the the initial elements of `s` are equal to `prefix`.
func startsWith<S0 : Sequence, S1 : Sequence where S0.GeneratorType.Element == S0.GeneratorType.Element, S0.GeneratorType.Element : Equatable>(s: S0, prefix: S1) -> Bool

func ~=<T : Equatable>(a: T, b: T) -> Bool
Closer examination of a selection of these will follow in a later post. For a list of all types and protocols that adopt, and inherit from, the Equatable protocol see this post.

Endorse on Coderwall

Comments