1

I have a struct the has a property of the same type. I'm getting an error

Value type '' cannot have a stored property that references itself

But this is not a reference to self. It's just a reference to a value of the same type.

If i change it to a class everything works (i need it to be a struct)

code:

public struct MockData {
    var data1: Int!
    var data2: String!
    var data3: MockData?
}

Why is this not compiling, what is the problem?

Thanks

ilan
  • 4,402
  • 6
  • 40
  • 76
  • 1
    Code which does not compile and run cannot have retain cycles. structs are value types and cannot have references. – Martin R Dec 19 '16 at 09:45
  • @MartinR I don't think you choose a good dup target. This question have nothing to do with retrain/reference cycle. It is more about recursive struct with impossible to calculate size. – Bryan Chen Dec 19 '16 at 09:47
  • @MartinR can you explain what do you mean by this : " structs are value types and cannot have references" – ilan Dec 19 '16 at 09:48
  • @BryanChen: The accepted answer explains: *"When capturing and storing value types (structs and enums), there is no such thing as a reference. ..."* Another answer offers a solution (indirect enums). – Martin R Dec 19 '16 at 09:49
  • 1
    @MartinR I think a good answer (at least the one I was writing) should mention that struct must have compile-time calculable size. In this case, `MockData` have a member of an `Optional`, which is also a struct, that holding a member of `MockData`, making the struct size not possible to be calculated. – Bryan Chen Dec 19 '16 at 09:53
  • thanks @BryanChen now i understand the problem. – ilan Dec 19 '16 at 09:54
  • Here is another one: [Swift struct type recursion](http://stackoverflow.com/questions/36080491/swift-struct-type-recursion). Or this one [Swift struct type recursive value](http://stackoverflow.com/questions/38785551/swift-struct-type-recursive-value). – Martin R Dec 19 '16 at 09:55
  • It does answer the struct part, but maybe confusing if people think `Optional` is kind of a pointer rather than a struct. – Bryan Chen Dec 19 '16 at 09:56
  • @BryanChen and MartinR i didn't know that a struct size needs to be calculated on compile time. thanks – ilan Dec 19 '16 at 09:59
  • 3
    Also related: [Structs that refer to each other in Swift 3](http://stackoverflow.com/q/40771706/2976878) – another solution would be to create your own wrapper type to provide indirection. – Hamish Dec 19 '16 at 10:00

0 Answers0