I have been trying to figure out if I can create a class or struct with a property that is of the same class or struct. An example would be

struct Number { 
    var Value: Int = 0
    var Rate: Number() //Default value for rate would be 0

Effectively this would be a recursive line of code but I don't want it to execute more than one iteration down. That is to say, if I have a timer to increment all Numbers by their given rates. But some of the rates also have rates also need to be incremented with the timer. I could declare all all of the individual properties and their prospective rates, but this seemed like a potentially good way to save on code. I just can't seem to wrap my head around the recursive nature of the idea. Declaring a variable that declares a variable that declares a ...

If anyone would be willing to help me understand how this would work, I would be very grateful.

1 Answer 1


Making it a struct would be problematic for obvious reasons. If you make it a class however you will be fine.

The Rate member would initially be null or you could have Rate's constructor create a Rate instance but that would have to be done conditionally: only when the Rate object's parent is null. You would pass parent to the constructor as an argument. This would give you your one-level deep nested Rate object.

  • Ah, this makes sense. So the way to write the code for this would be to change the line for rate to var? Rate: Number() or whatever it needs to be in the given language. I think I'm kind of mixing up languages but I'm trying to learn several at once. That makes sense.
    – Timothy
    Commented Jul 2, 2021 at 3:05
  • @Timothy You must make Rate a class and you do not need the ? after var. I assume the ? declares a nullable (value) type which would still be a struct, which occupies a fixed amount of inline memory. This would recursively deplete memory if the compiler would allow you to do this. A class would make the Rate member a reference which would be fine. I am not entirely sure your compiler will handle nullable types in structs the way I described, it may default to references after all and also work but then it would defeat the purpose of using structs. Anyway, you may want to try both. Commented Jul 2, 2021 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.