Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple variable assignment in Swift

How do I assign multiple variables in one line using Swift?

    var blah = 0     var blah2 = 2      blah = blah2 = 3  // Doesn't work??? 
like image 215
hamobi Avatar asked Oct 02 '14 06:10

hamobi


People also ask

How to assign same value to multiple variables in Swift?

We can assign values to multiple variables at once in a single statement in Swift. We need to wrap the variables inside a bracket and assign the values using the equal sign = . The values are also wrapped inside a bracket.

How do I declare multiple variables in Swift?

You can declare multiple constants or multiple variables on a single line, separated by commas: var x = 0.0, y = 0.0, z = 0.0.

How do you do multiple assignments with multiple variables?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

How do you assign an array to a variable in Swift?

If you assign a created array to a variable, then it is always mutable, which means you can change it by adding, removing, or changing its items; but if you assign an array to a constant, then that array is immutable, and its size and contents cannot be changed.


Video Answer


1 Answers

You don't.

This is a language feature to prevent the standard unwanted side-effect of assignment returning a value, as described in the Swift book:

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.

So, this helps prevent this extremely common error. While this kind of mistake can be mitigated for in other languages—for example, by using Yoda conditions—the Swift designers apparently decided that it was better to make certain at the language level that you couldn't shoot yourself in the foot. But it does mean that you can't use:

blah = blah2 = 3 

If you're desperate to do the assignment on one line, you could use tuple syntax, but you'd still have to specifically assign each value:

(blah, blah2) = (3, 3) 

...and I wouldn't recommend it. While it may feel inconvenient at first, just typing the whole thing out is the best way to go, in my opinion:

blah = 3 blah2 = 3 
like image 155
Matt Gibson Avatar answered Sep 23 '22 04:09

Matt Gibson