Recursive value types, structs

I'm wanting to do something similar like this:


struct Category {
let id: Int
let parent: Category?
}


And getting the error "Recursive value type 'Category' is not allowed".


Anyway around this?

Depending on your actual use case and requirements, you can do something like this:

protocol CategoryType {
var id: Int { get }
}
struct Category<Parent: CategoryType> {
let id: Int
let parent: Parent?
}


Or this:

struct Category {
let id: Int
let parent: Box<Category>?
}
class Box<T> {
let boxed: T
init(_ thingToBox: T) { boxed = thingToBox }
}


Or this:

indirect enum Category {
case Root(id: Int)
case Node(id: Int, parent: Category)
}


Or this:

enum Category {
case Root(id: Int)
indirect case Node(id: Int, parent: Category)
}



Or you can of course use classes if you don't really need value semantics. Alternative 2 above requires some more work/thinking in order to get it to behave the way you want/expect, since it is boxing the parent in a class (for the indirection).


In general, if you want value semantics, you also have to think through what that means for the implementation of your particular type.

Eg, what happens when you copy a category from a hierarchy of categories, do they share a reference to same parent until you mutate something (copy on write)? Or does it copy the parent and its parent etc.?

If you haven't already, you can watch the WWDC 2015 video Building Better Apps with Value Types in Swift. And you can also read about how Swift's Array type is implemented.

Recursive value types, structs
 
 
Q