0

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation! I use the semicolons so I won't forget them when I write code in C. Thanks! +1
1

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"]

2 Comments

Clear, thank you! I'll accept that answer as soon as I can.
I might argue the opposite. We want are code to be verbose, as verbosity generally makes code more clear. But array literals are a case where there's a concise alternative which is actually more clear. Ultimately we want the most clear version of the code, but when in doubt, err on the side of more verbose.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.