简体   繁体   中英

Convert a Objective C Self Referential Struct to Swift

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM