Defeat the hassle of treating C arrays as Tuples in Swift


Working with C fixed-length arrays is a bit annoying when using the C library from Swift. That's because Swift treats it as a Tuple. Tuple is not Iteratable, so it is difficult to refer to elements. What to do with this?


Method 1: Defeat with reflection

How to convert Tuples to Arrays with reflection, as described at There is no problem. However, reflection is a heavy load on the Compiler and is not the method you want to use aggressively.

Method 2: Defeat with a pointer

var foo_list = func_with_c()
let ptr = UnsafeMutablePointer<Foo>(&

// "Fixed length"Write the size of. For example, suppose you know that the length is 34.
for i in 0..<34 {
    let foo = ptr[i]

I'm not happy to use var, but it's compiler friendly because it doesn't do reflections. I wonder if I often write like this unless there is a particular reason ..?

Reference: Swift Foundation UUID implement

Recommended Posts

Defeat the hassle of treating C arrays as Tuples in Swift
Find the approximate value of log (1 + x) in Swift
I translated [Clone method for Java arrays] as the Clone method in Java arrays.
Implement the same function as C, C ++ system ("cls"); in Java
[Swift5] How to get an array and the complement of arrays
[Swift] Determine the constellation from the date of birth entered in the UIDatePicker
[Swift] Change the textColor of UIDatePicker
The basic basis of Swift dialogs
Handle C char ** well in Swift
Order of processing in the program