how to overload an assignment operator in swift
Asked Answered
H

3

29

I would like to override the '=' operator for a CGFloat like the follow try :

func = (inout left: CGFloat, right: Float) {
    left=CGFloat(right)
}

So I could do the following:

var A:CGFloat=1
var B:Float=2
A=B

Can this be done ? I get the error Explicitly discard the result of the closure by assigning to '_'

Homogeny answered 30/4, 2015 at 9:38 Comment(2)
You cannot overload the assignment operator - only compound assignment (like += etc.)Teddy
@Teddy is right, here is the reference for it: developer.apple.com/library/ios/documentation/Swift/Conceptual/…Scotsman
T
34

That's not possible - as outlined in the documentation:

It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.

If that doesn't convince you, just change the operator to +=:

func +=(left: inout CGFloat, right: Float) {
    left += CGFloat(right)
}

and you'll notice that you will no longer get a compilation error.

The reason for the misleading error message is probably because the compiler is interpreting your attempt to overload as an assignment

Teddy answered 30/4, 2015 at 9:59 Comment(0)
F
12

You can not override assignment but you can use different operators in your case. For example &= operator.

func &= (inout left: CGFloat, right: Float) {
    left = CGFloat(right)
}

So you could do the following:

var A: CGFLoat = 1
var B: Float = 2
A &= B

By the way operators &+, &-, &* exist in swift. They represent C-style operation without overflow. More

Falsework answered 18/2, 2016 at 8:46 Comment(0)
O
1

This is NOT operator overload approach. But the result may be what you are expecting

// Conform to `ExpressibleByIntegerLiteral` and implement it
extension String: ExpressibleByIntegerLiteral {
    public init(integerLiteral value: Int) {
        // String has an initializer that takes an Int, we can use that to
        // create a string
        self = String(value)
    }
}

extension Int: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        self = Int(value) ?? 0
    }
}

// No error, s2 is the string "4"
let s1: Int = "1"
let s2: String = 2

print(s1)       //output: 1
print(s2)       //output: 2
print(s1 + 2)   //output: 3 instead of "12"
Overwork answered 15/4, 2021 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.