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?
In Python, use the = operator to assign values to variables. You can assign values to multiple variables on 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.
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 .
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With