Home > Net >  How can I get access or overridden the = operator in Swift?
How can I get access or overridden the = operator in Swift?

Time:08-21

There is possibility in Swift for defining new custom operators like infix operator ** but I do not want define a new operator, I want get access to the function or logic of = in Swift.

Here is what I am think about = operator, this code is just for show case and it does not work.

infix operator =
func =<T>(rhs: T) {
    // My custom code is here:
    print("rhs=",rhs)
    self = rhs
}

So how can I get access or even overridden = operator in Swift?

CodePudding user response:

You can not override the assignment operator (=), from the Swift Programming Language book

NOTE It isn’t possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) can’t be overloaded.

Quote from this chapter

CodePudding user response:

You want to override =, the assignment operator, not ==, the equality operator?

I don't think the assignment operator can be overridden.

However, You can define custom setters for any instance variable. That has the same effect as overriding the assignment operator. Consider this code:

class Foo {
    init(bar: Int) {
        self._bar = bar
    }
    public var bar: Int {
        get {
            return _bar
        }
        set {
            // You can put any code you want in the setter.
            print("Setting bar to \(newValue)")
            _bar = newValue
        }
    }
    private var _bar: Int
}

var aFoo = Foo(bar: 1)

aFoo.bar = 12
print("aFoo.bar = \(aFoo.bar)")

That logs

Setting bar to 12

aFoo.bar = 12

To the console.

CodePudding user response:

Is it the = or the == ? for == You have to implement Equatable protocol, here is a snippet:

struct Money: Equatable {
    let value: Int
    let currencyCode: String

    static func == (lhs: Money, rhs: Money) -> Bool {
        lhs.currencyCode == rhs.currencyCode && lhs.value == rhs.value
    }
}

Theres a complete article here: Operator overloading/custom operators

  • Related