Z4ckZ3r0
Z4ckZ3r0

Reputation: 113

Passing class by value

I'm new to Swift so please let me know if I've missed something painful obvious. I have a class that I want to pass by value to overload the + operator.

The code won't work if I define the left argument lhs as foo but then it is immutable, and will work if lhs is inout foo, but then I have modified lhs which I clearly do not want.

A quick breakdown of my class:

class foo<T: Numeric> {
    /* Data */
    /* Init Fn */
    /* += definition */
    static func + (lhs: foo, rhs: foo) -> foo {
        do {
            try lhs += rhs
            return lhs
        } catch {
            /* Error Handling */
        }
    }
}

I come from a C++ background, so I am surprised that I am unable to pass the object by value if I choose. Following the question What are the basic rules and idioms for operator overloading?, in C++ this overloading method would expect the left argument to be passed by value and the right argument to be passed by const & as shown below, but here I don't seem to have that option.

class X {
    /* In Swift operators are not defined internally like this */
    X& operator+=(const X& rhs) {
        // actual addition of rhs to *this
        return *this;
    }
};
inline X operator+(X lhs, const X& rhs) {
    lhs += rhs;
    return lhs;
}

Is there a way that I don't know about, or is overloading done differently in Swift?

Any help would be greatly appreciated.

Upvotes: 1

Views: 269

Answers (1)

Sulthan
Sulthan

Reputation: 130102

I don't see any real problem with mutability. Note that with classes, without passing-by-value, you just cannot use one operator to define the other one.

class Foo<T: Numeric> {
    var value: T

    init(value: T) {
        self.value = value
    }

    static func + (lhs: Foo, rhs: Foo) -> Foo {
        return Foo(value: lhs.value + rhs.value)
    }

    static func += (lhs: Foo, rhs: Foo) {
        lhs.value += rhs.value
    }
}

let ten = Foo<Int>(value: 10)
let eighteen = ten + Foo<Int>(value: 8)
eighteen += Foo<Int>(value: 1)

Upvotes: 2

Related Questions