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 '_'

Slipp D. Thompson
  • 33,165
  • 3
  • 43
  • 43
mcfly soft
  • 11,289
  • 26
  • 98
  • 202
  • 3
    You cannot overload the assignment operator - only compound assignment (like `+=` etc.) – Antonio Apr 30 '15 at 09:43
  • 1
    @Antonio is right, here is the reference for it: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html – Dániel Nagy Apr 30 '15 at 09:53

3 Answers3

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

kelin
  • 11,323
  • 6
  • 67
  • 104
Antonio
  • 71,651
  • 11
  • 148
  • 165
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

fnc12
  • 2,241
  • 1
  • 21
  • 27
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)
print(s2)
print(s1 + 2)
Pham Quan
  • 131
  • 2
  • 4