PeterPan
PeterPan

Reputation: 744

Creating arrays

I'm about to learn Swift 2 and got to the chapter about arrays. There I found out that both of the following do (at least what I can see) the same:

First one:

var shoppinglist = [String](arrayLiteral: "Eggs", "Milk");

Second one:

var shoppinglist2: [String] = ["Eggs", "Milk"];

What exactly is the difference between those two or is there no difference at all? Which one should I prefer?

Upvotes: 0

Views: 72

Answers (3)

Joachim Olsson
Joachim Olsson

Reputation: 316

The second one is more common, in this case you can also exclude : [String] because it's inferred from the right hand side value. They have different syntax but evaluate to the same thing. The first one is commonly used when creating either empty arrays or repeated arrays like this:

var empties = [Float]()
var doubles = [Double](count: 15, repeatedValue: 1.0)

Upvotes: 1

algal
algal

Reputation: 28104

There is no functional difference but you should prefer the second expression.

The syntax [String] is just a shorthand for Array<String>, which says that you are describing the generic Array type specialized to hold String values.

However, it's more common and readable to use that shorthand syntax just to describe a type, not to actually invoke the initializer, as you are doing in the first example. Also, there's no need to call the initializer that takes the arrayLiteral parameter. The point of that parameter is to allow you to initialize an array with a literal, as you are doing in the second example.

Your second example is good.

Another option is simply

var shoppinglist3 = ["Eggs", "Milk"]

which relies on type inference.

And you don't need the semicolons

Upvotes: 2

Luke De Feo
Luke De Feo

Reputation: 2165

Its just syntactic sugar to make your code less verbose, you should in general prefer less verbose code unless it is for some reason unclear. Also you can drop the type annotation since it is redundant as the type can be inferred from the expression.

So ideally:

var shoppinglist = ["Eggs", "Milk"]

Upvotes: 1

Related Questions