Tuesday, April 23, 2019

Equatable and Comparable protocol in Swift

In Swift, sort, sorted have two parameter types, one does not have parameter, another one takes a closure.
mutating func sort()
mutating func sort(by areInIncreasingOrder: (Element, Element) throws -> Boolrethrows

Similar for contains method, one takes an element parameter, and another one take a closure.

func contains(_ element: Element) -> Bool
func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool

Which one to use depends on whether the element type conforms to Equatable (for contains method) or Comparable (for sort method) protocol.

When calling sort or contains method with the closure parameter, there is no limitation on element type, so any element can be used for those methods.

However, when calling contains method with an element object parameter, the element type must conforms to Equatable protocol. Equatable protocol defines a == method, so == can be used in swift code to compare whether two elements are equal or not. When contains(element: Element) is called, it internally uses Equatable protocol's == method to compare whether the input parameter is contained in the collection.

Similarly, when calling sort method with empty parameter, the element type must conforms to Comparable protocol. Comparable protocol inherits from Equatable protocol, which defines some additional method of >  <  >=  <=, so those operators can be used to compare two element objects' value in swift code, Sort method internally uses those method to sort the elements in a collection.

In a word, if an element types conforms to Equatable (or Comparable) protocol, then the simple version of sort (or contains) method can be used, otherwise, the one with the closure parameter must be used. 

No comments:

Post a Comment