SoFunction
Updated on 2025-04-11

Detailed explanation of Swift's operator overloading example

introduction

In C++, operators can be overloaded, and Swift is also supported

Note:=and trinocular operatorsa ? b : cNot reloadable

Overload the binocular operator

class Vector {
    var x: Double = 0.0
    var y: Double = 0.0
    var z: Double = 0.0
    init(x: Double, y: Double, z: Double) {
         = x
         = y
         = z
    }
    convenience init() {
        (x: 0, y: 0, z: 0) 
    }
    /// Operator '+' declared in type 'Vector' must be 'static'
    /// + is a binocular operator with two parameters    static func +(v1: Vector, v2: Vector) -> Vector {
        let vector: Vector = Vector()
         =  + 
         =  + 
         =  + 
        return vector
    }
}

Monologic operator

Classes and structures can also implement monolog operators, which only operate one value.

The operator appears before the value and is a prefix operator (prefix, such as -a), and appears after the value and is a postfix operator (postfix, such as a!).

struct Coordinate {
    var x: Double = 0.0
    var y: Double = 0.0
    static prefix func +(coordinate: Coordinate) -> Coordinate {
        return Coordinate(x: +, y: +)
    }
    static prefix func -(coordinate: Coordinate) -> Coordinate {
        return Coordinate(x: -, y: -)
    }
}
func test() {
    let p1 = Coordinate(x: 1.0, y: 1.0)
    let p2 = Coordinate(x: 2.0, y: 2.0)
    print(-p1) // Coordinate(x: -1.0, y: -1.0)
    print(+p2) // Coordinate(x: 2.0, y: 2.0)
}

Compound assignment operator

Compound assignment operators are combinations of assignment operators (=) and other operators, such as +=, -=

struct Coordinate {
    var x: Double = 0.0
    var y: Double = 0.0
    // If placed in a global function, static is not required, otherwise static cannot be omitted    static func +=(left: inout Coordinate, right: Coordinate) {
        left = Coordinate(x:  + , y:  + )
    }
    static func -=(c1: inout Coordinate, c2: Coordinate) {
        left = Coordinate(x:  -  , y:  - )
    }
}
func test() {
    var p1 = Coordinate(x: 1.0, y: 1.0)
    let p2 = Coordinate(x: 2.0, y: 2.0)
    p1 += p2
    print(p1) // Coordinate(x: 3.0, y: 3.0)
}

Equivalent operator ==

Custom classes and structures do not implement the default implementation of equivalence operators. Equivalent operators are generally called equality operators==and unequal operators!=

struct Coordinate {
    var x: Double = 0.0
    var y: Double = 0.0
    static func ==(c1: Coordinate, c2: Coordinate) -> Bool {
        return  ==  &&  == 
    }
    static func !=(left: Coordinate, right: Coordinate) -> Bool {
        return  !=  ||  != 
    }
}
func test() {
    let p1 = Coordinate(x: 1.0, y: 1.0)
    var p2 = Coordinate(x: 2.0, y: 2.0)
    print(p1 == p2) // false
     -= 1
     -= 1
    print(p1 == p2) // true
}

Custom operators

You can customize prefix, postfix, middle operator infix, constraints:

  • Only the following characters can be used:
    - + * / = % < > ! & | ^ . ~
  • Only the central operator can inherit the priority group precdence (introduced later)
  • Custom operators cannot be placed in classes, they must be placed in file scope.

Custom post-operators

struct Coordinate {
    var x: Double = 0.0
    var y: Double = 0.0
}
// File scope, that is, global scope, cannot be under classprefix operator +++
prefix func +++(coordinate: inout Coordinate) -&gt; Coordinate {
     =  + 
     =  + 
    return coordinate
}
func test() {
    var p1 = Coordinate(x: 1.0, y: 1.0)
    print(+++p1) // Coordinate(x: 2.0, y: 2.0)
}

Custom pre-operators are similar to custom post-operators

postfix operator +++
postfix func +++(coordinate: inout Coordinate) -> Coordinate {
     =  + 
     =  + 
    return coordinate
}

Customize the central operator

precedencegroup MyPrecedence {
    // higherThan: AdditionPrecedence // Priority, higher than addition    lowerThan: AdditionPrecedence       // Priority, lower than addition    associativity: none                 // Combination direction: left, right or none    assignment: false                   // true means assignment operator, false means non-assignment operator}
infix operator +++ : MyPrecedence  // Inherit MyPrecedence priority group (optional)func +++(left: Int, right: Int) -&gt; Int {
    return (left + right) * 2
}
func test() {
    print(3+++2)
}

With the help of custom operators, we can wave it and define an operator. When there is a value, use this value and use the desired default value when there is no value, as shown below:

postfix operator <<<
postfix func <<<(a: String?) -> String { return a ?? "" }
func test() {
    print(getStr()<<<)
}
func getStr() -> String? {
    return nil
}

Example

postfix operator <<<
postfix func <<<(a: String?)              -> String              { return a ?? "" }
postfix func <<<(a: Int?)                 -> Int                 { return a ?? 0 }
postfix func <<<(a: Int8?)                -> Int8                { return a ?? 0 }
postfix func <<<(a: Int16?)               -> Int16               { return a ?? 0 }
postfix func <<<(a: Int32?)               -> Int32               { return a ?? 0 }
postfix func <<<(a: Int64?)               -> Int64               { return a ?? 0 }
postfix func <<<(a: UInt?)                -> UInt                { return a ?? 0 }
postfix func <<<(a: Double?)              -> Double              { return a ?? 0.0 }
postfix func <<<(a: Float?)               -> Float               { return a ?? 0.0 }
postfix func <<<(a: [AnyObject]?)         -> [AnyObject]         { return a ?? [] }
postfix func <<<(a: [String]?)            -> [String]            { return a ?? [] }
postfix func <<<(a: [Int]?)               -> [Int]               { return a ?? [] }
postfix func <<<(a: [String: AnyObject]?) -> [String: AnyObject] { return a ?? [:]}
postfix func <<<(a: [String: String]?)    -> [String: String]    { return a ?? [:] }

The above is the detailed explanation of the Swift operator overloading example. For more information about Swift operator overloading, please pay attention to my other related articles!