[swift-evolution] Overloading assignment operator
John McCall
rjmccall at apple.com
Mon Dec 7 00:45:54 CST 2015
> On Dec 6, 2015, at 10:17 PM, Don Wills <don.wills at portablesoftware.com> wrote:
> John,
>
>> On Dec 6, 2015, at 10:54 PM, John McCall <rjmccall at apple.com> wrote:
>>
>>> On Dec 6, 2015, at 5:44 AM, Don Wills via swift-evolution <swift-evolution at swift.org> wrote:
>>>
>>> The ability to overload operators is very useful. However, that utility is diminished without the ability to overload the simple assignment operator ( = ). I vaguely recall reading somewhere that there is a reason for this having to do with syntax ambiguity. Can this problem be solved so that = can be overloaded?
>>
>> In your specific case, I think Alex Lew is completely correct: you really don’t want a ton of overloaded operators, you just want your decimal type to be literal-convertible.
>>
>> But to answer the question more generally, no, I can’t foresee us ever allowing the overloading of =, no. = always means simple initialization/assignment in Swift; that is, it always simply propagates values around. That’s a very fundamental language concept to mess around with.
>
> I guess I missed the subtlety that in Swift the statement "x = y;" is fundamentally different than "x += y;". That surprises me.
It shouldn’t. I am not aware of any languages in which = (or its equivalent) is just a normal overloaded operator. Even in C++, (1) there are different formation rules for assignment operators, (2) assignment operators are often implicitly generated, (3) explicitly declared assignment operators can have subtle effects on formal language behavior, and (4) the resolution rules for assignment are different from the rules for other user-defined operators, even compound assignment.
Oh, and of course (5) the token “=" doesn’t mean assignment in the contexts where it actually means initialization, which is something that was actually confused earlier in this thread, and which is probably the single most common point of confusion among even quite knowledgeable C++ programmers — and which is, by and large, a problem that we’ve defined away in Swift by not introducing this kind of semantic confusion around the behavior of =.
> And it fails one of the basic principles that I've always applied to software design: The Principle of Least Astonishment.
In fact, in my experience, programmers tend to be quite astonished by the behavior of overloaded assignment.
Again, the feature you actually need for all of your examples is literal convertibility, which already exists; please look into it before writing off the language.
John.
> Thanks for your response, even though it is quite disheartening to me. As I get to know the nuances of Swift, I'm starting to think that moving to Swift might be too big of a stretch for my programming staff.
>
> Don Wills
More information about the swift-evolution
mailing list