0

Self referential Structs are possible in objective C. Eg:

typedef struct Sample {
    struct Sample* first;
    struct Sample* second;
    struct Sample* third;
} SampleStruct;

The swift conversion looks something like

struct Sample {
    var first: Sample?
    var second: Sample?
    var third: Sample?
}
typealias SampleStruct = Sample

But it throws a compiler error saying "Value type 'Sample' cannot have a stored property that references itself".

How do i convert the self referential struct to swift?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Allen Savio
  • 151
  • 2
  • 16

1 Answers1

3

You know you cannot define this sort of struct in Objective-C.

typedef struct Sample {
    struct Sample first;
    struct Sample second;
    struct Sample third;
} SampleStruct;

(Swift adds a hidden isNil... field for each Optional, but it's not a big difference.)

If you want to define an exact equivalent to your Objective-C code, you need to use pointers, as in the original code.

struct Sample {
    var first: UnsafeMutablePointer<Sample>?
    var second: UnsafeMutablePointer<Sample>?
    var third: UnsafeMutablePointer<Sample>?
}

Better consider using class as commented.

OOPer
  • 47,149
  • 6
  • 107
  • 142