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.
if
, if I'm not mistaken. So even ifi = 1
returnedif
,if i = 1 {}
wouldn't compile, since in Swift1
is not a boolean value. @greenoldman, thank you for the link) – Noellai = ++i + i++;
, which has undefined behavior in C and C++. – Linker