Optional array vs. empty array in Swift

Aaron Rasmussen picture Aaron Rasmussen · Nov 8, 2014 · Viewed 16.2k times · Source

I have a simple Person class in Swift that looks about like this:

class Person {
    var name = "John Doe"
    var age = 18
    var children = [Person]?

    \\ init function goes here, but does not initialize children array
}

Instead of declaring children to be an optional array, I could simply declare it and initialize it as an empty array like this:

var children = [Person]()

I am trying to decide which approach is better. Declaring the array as an optional array means that it will not take up any memory at all, whereas an empty array has at least some memory allocated for it, correct? So using the optional array means that there will be at least some memory saving. I guess my first question is: Is there really any actual memory saving involved here, or are my assumptions about this incorrect?

On the other hand, if it is optional then each time I try to use it I will have to check to see if it is nil or not before adding or removing objects from it. So there will be be some loss of efficiency there (but not much, I imagine).

I kind of like the optional approach. Not every Person will have children, so why not let children be nil until the Person decides to settle down and raise a family?

At any rate, I would like to know if there are any other specific advantages or disadvantages to one approach or the other. It is a design question that will come up over and over again.

Answer

Nate Cook picture Nate Cook · Nov 8, 2014

I'm going to make the opposite case from Yordi - an empty array just as clearly says "this Person has no children", and will save you a ton of hassle. children.isEmpty is an easy check for the existence of kids, and you won't ever have to unwrap or worry about an unexpected nil.

Also, as a note, declaring something as optional doesn't mean it takes zero space - it's the .None case of an Optional<Array<Person>>.