Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class or struct for hierarchy model?

Tags:

swift

I understand difference between class and struct in Swift. Now I'm wondering what to use for hierarchy model.

To define a class is pretty simple (setting connections on properties set is now irrelevant).

class XYClass {
    var title: String
    var subinstances: [XYClass]
    weak var superinstance: XYClass?
}

But it looks like pretty fine model for struct. Especially if I need to instantiate a lots of these and frequently. But I'm wondering if I can somehow safely point to superinstance or I need to store whole object graph to every instance on every change... Should I use class or struct and if struct, how to define it?

like image 410
user500 Avatar asked Sep 01 '26 02:09

user500


1 Answers

You are making a linked list. If you were to try to form a linked list of structs of a single type, memory management would not be feasible, and the compiler would stop you dead in your tracks. This won't compile:

struct XYClass {
    var title: String
    var subinstances: [XYClass]
    var superinstance: XYClass?
}

The compiler has spotted the problem. You cannot refer to an instance of a struct as a property of that struct. (The compiler calls this a "recursive value type".)

Thus, for your situation, you must use a class, because only then can you get a weak reference and avoid a retain cycle. Only a reference to a class can be weak (and only if the reference is typed as an Optional).

This will compile, and will give your linked list coherent memory management:

class XYClass {
    var title: String = ""
    var subinstances: [XYClass] = []
    weak var superinstance: XYClass?
}
like image 186
matt Avatar answered Sep 03 '26 23:09

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!