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.
question from:https://stackoverflow.com/questions/26811787/optional-array-vs-empty-array-in-swift