Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize multiple variables of some type in one line

Tags:

swift

I want to achieve something like

var a, b, c: MyType = MyType()

but this line doesn't compile because compiler treats the type annotation MyType is only for variable c thus a and b are missing either type annotation or a initial value for type inference.

Both of followings are legal :

// legal but verbose
var a = MyType()
var b = MyType()
var c = MyType()

// legal but verbose to initialize
var a, b, c: MyType
a = MyType()
b = MyType()
c = MyType()

These two styles I can think of are both legal but somehow verbose, especially if there are dozens of variables of same type.

Is there any elegant way to achieve this?

like image 848
Nandin Borjigin Avatar asked Dec 17 '16 07:12

Nandin Borjigin


People also ask

Can you initialize multiple variables in one line?

In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.

How do you define multiple variables in one line?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.

How do you declare multiple variables in one line in Java?

Declaring and Assigning Variables You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .

Is it possible to declare multiple types of variables in single?

It is also possible to declare multiple variables in a single line using short hand syntax. The above program declares two variables name and age of type string and int respectively.


1 Answers

You can declare multiple constants or multiple variables on a single line, separated by commas:

var a = "", b = "", c = ""

NOTE

If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

Documentation HERE.

In your case:

var a = MyType(), b = MyType(), c = MyType()
like image 60
Adrian Bobrowski Avatar answered Oct 08 '22 07:10

Adrian Bobrowski