Swift: Definition of overloaded operators


(0 comments)

In order to avoid the compiler from complaining and requesting data type conversion, when doing addition a Double number plus an Int number the operator + needs to be overloaded. In the code below, the four binary operators +, -, *, / are overloaded where the left side is a Double and the right side is an Int

extension Double {
    static func + (left: Double, right: Int) -> Double {
        return left + Double(right)
    }
}
extension Double {
    static func - (left: Double, right: Int) -> Double {
        return left - Double(right)
    }
}
extension Double {
    static func * (left: Double, right: Int) -> Double {
        return left * Double(right)
    }
}
extension Double {
    static func / (left: Double, right: Int) -> Double {
        return left / Double(right)
    }
}

 

Defining a new assignment to copy data of class objects
The default assignment = in Swift is impossible to overload. If we do not define a new assignment, the assignment to a class object only copies the reference, not the data. In the program below we declare the new assignment ==== under the AssignmentPrecedence group and define the assignment in the MyClasss class to copy data between two class objects

infix operator ====: AssignmentPrecedence

class MyClass {
    var i: Int
    init(_ i: Int) { self.i = i }
    static func ==== (left: inout MyClass, right: MyClass) {
        if left === right { return }
        left.i = right.i
    }
}

var a = MyClass(5)
var b = MyClass(0)
let b_orig = b

// a and b are the same, do nothing
b = a
b ==== a

// copy data
b = b_orig
b ==== a

a.i = 8
print(a.i, b.i)

Currently unrated

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required


What is 10 + 5?

required