× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

how to overload an assignment operator in swift

Antonio Bello
May 07, 2015
<p>That's not possible - as outlined in the <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID44" rel="nofollow">documentation</a>:</p> <blockquote> <p>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.</p> </blockquote> <p>If that doesn't convince you, just change the operator to <code>+=</code>:</p> <pre><code>func += (inout left: CGFloat, right: Float) { left = CGFloat(right) } </code></pre> <p>and you'll notice that you will no longer get a compilation error.</p> <p>The reason for the misleading error message is probably because the compiler is interpreting your attempt to overload as an assignment</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29964177/how%20to%20overload%20an%20assignment%20operator%20in%20swift/29964643">Stack Overflow</a>.</p>
comments powered by Disqus