Reputation: 29518
I tried searching around for what this is
[]()
But I'm not really sure. In a playground, I did this:
var test = [Int]();
test.append(1);
test.append(2);
If I leave off the () and do
var test = [Int];
test.append(1);
test.append(2);
It still looks like an array of Ints to me. What is the difference?
Upvotes: 2
Views: 535
Reputation: 535944
Type()
means "call init()
" - i.e., make a new instance of Type
.
[Int]
is a type, like String
. [Int]
means "array-of-Int".
String()
makes a new empty String instance. [Int]()
makes a new empty array-of-Int instance.
You can declare a variable as being of type array-of-Int. Or you can make and assign a new array-of-Int instance. Which is what you are doing here:
var test = [Int]()
But you cannot assign a type to a variable without further syntax. Thus, this is illegal:
var test = [Int]
EXTRA for experts
You can say:
var test = [Int].self
That does assign the type to the variable! That is unlikely to be what you want here, because now you have no array; you have a type, itself, as object!!
Upvotes: 5
Reputation: 72780
[Type]
is syntactic sugar for Array<Type>
, so it represents the array type, which is a generic struct, and for which you specify the type of elements it holds (Int
in this example)
So the difference between:
[Int]
and
[Int]()
is the same as for
Array<Int>
and
Array<Int>()
The first is just a type, which you can use when declaring a variable or a function parameter.
The second invokes the parameterless constructor on that type, i.e. creates an instance of that type.
Upvotes: 0