I want to define a struct that contains a fixed-size blob of data — for example, a SHA-1 digest, which is 20 bytes long. Is there any way to define this in Swift such that the data lives
in the struct, instead of being a separate heap block?
In other words, I want the Swift equivalent of
typedef struct {
char bytes[20];
} SHA1Digest;
I couldn’t find anything in either official Swift book about working with C arrays. The closest thing is the section “Pointers” in Using Swift With Cocoa, but it only seems to talk about calling other Swift code.
As far as I can tell, to get a block of n bytes (where n is known at compile time) I have to use an Array. Which implies creating a separate internal object to store the array contents. This isn’t very inefficient if I only have a couple of these, but if I’ve got millions of them, or need to process them at a very high rate (i.e. in some numeric or crypto code) it can be a big bottleneck — this is the sort of reason why people fall back to C or C++ when doing computation-intensive code.
Go can handle this just fine (a fixed-size array, as opposed to a slice, needn’t be heap-allocated, and is copied by value) and I was imagining Swift could too, until I tried to create such a thing today and got stuck.
—Jens