C-like array inside a struct

Hello all,

Does anyone know if there is a way to have a C-like array inside a struct ?

I would like to have the memory for the array allocated alongside the struct, not somewhere else on the heap. The goal is to avoid the extra memory allocation because of the array.

It is fine if the array can not grow like Swift array, of course.

struct MyStruct {
    var myValue: Int
    var myArray: [Int8] = .init(repeating: 0, count: 100)
    // ^ here, I would like the items of myArray allocated inside MyStruct
}

I think that people generally use (big) tuples for that purpose.

Thanks Morten !

Any other ways than tuples ? I cannot imagine to have a tuple containing 100 items for example.

Furthermore there is no subscript available on tuples .

I wonder why something so simple like that is not in the Swift language. Maybe some Swift guru could explain the reason why ??

Tuples are the way to do it. There have been a number of proposals for alternatives, such as Proposal: Contiguous Variables (A.K.A. Fixed Sized Array Type). I don't believe there is a profound reason that it isn't present, but it causes trickiness in the type system, and just generally has not been worked through at this time.

Thanks Cory for the link to this proposal, I hope this will be adopted one day ...

Following the discussions in the forum, I have gathered some interesting ideas about fixed size arrays:

Terms of Service

Privacy Policy

Cookie Policy