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:

func fetchBookByID(id: Int) // ...

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):

var titles1: [String] = []

Why not instead initialize it like this?

var titles2 = [String]()

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:

let bookStore = BookStore()
let book = bookStore.fetchBookByID(1)
// ...
var titles = [String]()
// ...

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.