Tiny Swift Tip: Initializing Empty Arrays

If you’re initializing your empty arrays by specifying the type annotation like this…

Hold on — what’s a type annotation?

Great question. You use them all the time when you define methods that have at least one parameter:

The : Int is the type annotation for the id parameter. A type annotation starts with a colon and ends with a type. Pretty simple, right?

Now, back to creating an empty array with a type annotation (which I don’t recommend):

Why not instead initialize it like this?

The second approach saves us a colon (🎉), but much more importantly, it makes our codebase more consistent since we don’t specify type annotations on most of our other variables. So the titles2 approach above looks more consistent when we’re also defining variables like this:

Use type annotations when necessary — but only when necessary. Initialize your empty arrays without type annotations and take advantage of the amazing type inference Swift provides.