Swift static func == (lhs: XXX, rhs: XXX) -> Bool

Swift static func == (lhs: XXX, rhs: XXX) -> Bool

It’s been a long time since I last wrote code. While I was programming, I encountered something I don’t understand. Why is the symbol ‘==’ used in function names?"

1
static func == (lhs: Person, rhs: Person) -> Bool { 

After studying, I realized that “==” is simply the equality operator in programming, used to compare two values to see if they are equal. LOL!

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Person: Equatable {
    
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    // Symbol "==" used in function
    // Here I have set two conditions: 
    // if both the name and age are the same,
    // then they are the same person.
    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.name == rhs.name && lhs.age == rhs.age
    }
}

Example:

1
2
3
4
5
6
let p1 = Person(name: "David", age: 18)
let p2 = Person(name: "David", age: 18)

if p1 == p2 {
    print("It's the same person")
}

Comparable same as ==

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public protocol Comparable: Equatable {
  static func < (lhs: Self, rhs: Self) -> Bool
  static func <= (lhs: Self, rhs: Self) -> Bool
  static func >= (lhs: Self, rhs: Self) -> Bool
  static func > (lhs: Self, rhs: Self) -> Bool
}

extension Comparable {

  @inlinable
  public static func > (lhs: Self, rhs: Self) -> Bool {
    return rhs < lhs
  }

  @inlinable
  public static func <= (lhs: Self, rhs: Self) -> Bool {
    return !(rhs < lhs)
  }

  @inlinable
  public static func >= (lhs: Self, rhs: Self) -> Bool {
    return !(lhs < rhs)
  }
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy