Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What was the reason for Swift assignment evaluation to void?

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.

like image 347
greenoldman Avatar asked Dec 09 '15 07:12

greenoldman


1 Answers

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.

like image 178
Brad Larson Avatar answered Sep 18 '22 14:09

Brad Larson