Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Collections and Control Flow Introduction to Collections Adding Items to Arrays

Agustin Hernandez
Agustin Hernandez
2,747 Points

Creating Empty Arrays

What's the difference when declaring an empty array

          // like this
          var someArray: [SomeType]
          // Or like this
          var someArray = [SomeType]()

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

In the first case:

var someArray: [SomeType]

You have declared but not initialised your array. If you wanted to use this style to declare an empty array, you would have written:

var someArray: [SomeType] = []

The second case:

var someArray = [SomeType]()

is exactly equivalent to var someArray: [SomeType] = []. The difference is purely personal style preference. Apple uses both in their own documentation, see here and here

First line is that you have declared your array but didn't assign anything (technically you just gave a name but no value)

Second line of code, you have named your array and assigned an empty/placeholder value in it.