问题
This question is about HISTORY (not your current opinions on the matter).
While reading post about dropping support for increment/decrement operators for Swift I read such text "Swift already deviates from C in that the =, += and other assignment-like operations returns Void (for a number of reasons)".
So at some time in the past developers consciously decided to evaluate assignments to void for some reasons.
And I am looking for those historical (now) reasons. Pretty much as this thread is about historical reasons for Scala.
回答1:
At least one reason is to be safer in comparison operations. When writing in C, Objective-C, etc., how many times have you written this:
if (x = 2)
instead of
if (x == 2)
Newer versions of compilers have introduced specific warnings for the above case, but wow has that one missing equal sign caused hard-to-identify bugs in my code over the years.
With the Swift type system, this would be less of a problem, since the returned value would most likely not comply to the BooleanType protocol, but if it did (if x = false
), you might still hit these bugs. A lot of Swift is designed to eliminate common causes of bugs that people have encountered, including this one.
This is stated in the Swift Programming Language book, under "Basic Operators":
Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value. The following statement is not valid:
if x = y { // this is not valid, because x = y does not return a value }
This feature prevents the assignment operator (=) from being used by accident when the equal to operator (==) is actually intended. By making if x = y invalid, Swift helps you to avoid these kinds of errors in your code.
来源:https://stackoverflow.com/questions/34173084/what-was-the-reason-for-swift-assignment-evaluation-to-void