In programs we use operators like "==" to compare things. But for some objects, we must define custom operators for equality.
And in rare situations, custom operators (not known to Swift) are helpful. This rapidly becomes complex. It can lead to code that is hard to read.
Here we define equality and inequality operators. We specify a simple class
called Box. On it we have a name String
.
func
keyword we create a global method that compares two Boxes (a left Box and aright Box).class Box { var name: String? } func == (left: Box, right: Box) -> Bool { // Compare based on a String field. return left.name == right.name } func != (left: Box, right: Box) -> Bool { // Return opposite of equality. return !(left == right) } // Create three Box instances. var box1 = Box() box1.name = "blue" var box2 = Box() box2.name = "blue" var box3 = Box() box3.name = "red" // Compare the instances with equality operator. if box1 == box2 { print(true) } // Use inequality operator. if box1 != box3 { print(false) }true false
Swift provides many language features for creating custom operators. This is an impractical example—it leads to unreadable code.
class
. The Plane contains one field: an Int
called "airborne."// Declare some operators. prefix operator ??? postfix operator ^^^ infix operator *** // This class is used in the operator funcs. class Plane { var airborne = 1 } // Implement 3 custom operators. prefix func ??? (argument: Plane) { argument.airborne -= 10 } postfix func ^^^ (argument: Plane) { argument.airborne *= 20 } func *** (left: Plane, right: Plane) { left.airborne = right.airborne } // Create objects to use with operators. var plane1 = Plane() var plane2 = Plane() print("1 = \(plane1.airborne), \(plane2.airborne)") // Use prefix operator. ???plane1 print("2 = \(plane1.airborne), \(plane2.airborne)") // Use postfix operator. plane2^^^ print("3 = \(plane1.airborne), \(plane2.airborne)") // Use infix operator. plane1***plane2 print("4 = \(plane1.airborne), \(plane2.airborne)")1 = 1, 1 2 = -9, 1 3 = -9, 20 4 = 20, 20
The previous example is not a good example of code. Using 3-character operators would not be a good choice for code that is meant to be used.
With an infix operator, we can define associativity and precedence. Some operators are grouped to the left or right—this is associativity.
Some languages have omitted operator overloading for clarity. Swift is not one of them. It has powerful, overloaded operators—this can lead to beautiful, concise, or unreadable code.