Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading equivalence (==) operator for custom class in Swift

Is it possible to overload equivalence (==) operator for a custom class inside that custom class. However I know that it is possible to have this operator overloaded outside class scope. Appreciate any sample code. Thanks in advance.

like image 937
Souandios Avatar asked Mar 04 '15 06:03

Souandios


People also ask

How to overload operator in Swift?

To overloading a prefix operator, we need to add a prefix keyword before a func . In the following example, I overload the - unary operator for a string, which will reverse the characters in a given string. <1> We add the prefix keyword to tell the compiler that this is intended to use as a prefix operator.

Is operator overloading supported in Swift?

Operator overloading is a powerful feature of Swift that can make development much more efficient, if you do it with care.

What is overloading in Swift?

In Swift, two or more functions may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These functions are called overloaded functions and this feature is called function overloading.

What is infix operator in Swift?

Examples of basic operators available in Swift A common example of an infix operator is the + sign which falls under the category Binary operators. It's called an infix operator as it appears in between two values. Swift also comes with a Ternary operator the operates on three targets.


2 Answers

Add global functions. For example:

class CustomClass {
    var id = "my id"
}

func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
    return lhs == rhs
}
func !=(lhs: CustomClass, rhs: CustomClass) -> Bool {
    return !(lhs == rhs)
}

To conform Equatable protocol in Swift 2

class CustomClass: Equatable {
    var id = "my id"
}

func ==(left: CustomClass, right: CustomClass) -> Bool {
    return left.id == right.id
}

To conform Equatable protocol in Swift 3

class CustomClass {
    var id = "my id"
}

extension CustomClass: Equatable {
    static func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
        return lhs.id == rhs.id
    }
}
like image 193
Yoichi Tagaya Avatar answered Sep 30 '22 04:09

Yoichi Tagaya


No, operators are overloaded using global functions.

like image 29
mipadi Avatar answered Sep 30 '22 04:09

mipadi