C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Equality: With the func keyword we create a global method that compares two Boxes (a left Box and a right Box).
FuncInequality: This is the "!=" operator and it returns the negation of the equality operator's result.
Bool: The equality and inequality operators must return Bool. This indicates whether the objects are equal (or in equal).
Result: We create 3 Box objects and compare them with our operators. The name field is used to determine equality and inequality.
Swift program that uses custom equality, inequality operators
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)
}
Output
true
false
However: The example uses the prefix, postfix, infix, associativity and precedence keywords.
Plane: We create instances of a simple Plane class. The Plane contains one field: an Int called "airborne."
Result: We define three 3-character operators and use them on our plane1 and plane2 objects. The "airborne" property is modified.
Swift program that uses prefix, postfix, infix
// Declare some operators.
prefix operator ??? {}
postfix operator ^^^ {}
infix operator *** { associativity left precedence 0 }
// 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)")
Output
1 = 1, 1
2 = -9, 1
3 = -9, 20
4 = 20, 20
However: It does show that the Swift language is extensible. If a custom operator is needed, these keywords could be helpful.
And: Some operators (like multiplication) have a higher precedence than others (like addition and subtraction).
Quote: Operator precedence gives some operators higher priority than others; these operators are applied first. Operator associativity defines how operators of the same precedence are grouped together.
Advanced Operators, Swift: apple.com