Weak object array in Swift

2.6k views Asked by At

I would like to create an object array as a property of another class in Swift, such as:

class person{
 var livingInHouse : house
 name : String
}
class house{
 var personArray : [person]
}

My constraints are:

  1. I would like to easily access the objects in the personArray using subscripts: e.g. houseInstance.personArray[1].name = "Steve"
  2. I would like to create the personArray so that the person objects are deallocated when houseInstance object is deallocated. What is the best method in Swift to do this?
1

There are 1 answers

0
Florian Burel On

From what you say, you want the person living in an house "alive" as long as their house is alive, so it is obvious that the house must "own" the persons.

Your class Person however just maintain a reference to the house for convenience, it doesn't own it (else it would be bad!)

so :

class house
{
    var personArray : person[]
}

class person
{
    unowned var livingInHouse : house
    name : String
}

You could then provide some convenience method to your house such as:

func add(Person p)
{
personArray += p;
p.livingHouse = self;
}