'How to initialize multiple variables of some type in one line

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?



Solution 1:[1]

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()

Solution 2:[2]

Two options in Swift: commas or tuples.

With commas separated statements:

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

With a tuple statement:

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

Also, but discouraged, you can make multiple statements on one line using semi-colons:

var a = MyType(); var b = MyType(); var c = MyType()

Solution 3:[3]

More smarter way to do this is

let type = (MyType(), MyType(), MyType())
var (a, b, c) = type

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrian Bobrowski
Solution 2 Cœur
Solution 3 Vikash Kumar Chaubey