Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,861 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.