Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access element of fixed length C array in swift

Tags:

swift

coremidi

I'm trying to convert some C code to swift. (Why? - to use CoreMIDI in OS-X in case you asked)

The C code is like this

void printPacketInfo(const MIDIPacket* packet) {
   int i;
   for (i=0; i<packet->length; i++) {
      printf("%d ", packet->data[i]);
   }
 }

And MIDIPacket is defined like this

struct MIDIPacket
 {
    MIDITimeStamp           timeStamp;
    UInt16                  length;
    Byte                    data[256];
 };

My Swift is like this

func printPacketInfo(packet: UnsafeMutablePointer<MIDIPacket>){
    // print some things
    print("length", packet.memory.length)
    print("time", packet.memory.timeStamp)
    print("data[0]", packet.memory.data.1)
    for i in 0 ..< packet.memory.length {
      print("data", i, packet.memory.data[i])
    }
  }

But this gives a compiler error

error: type '(UInt8, UInt8, .. cut .. UInt8, UInt8, UInt8)' has no subscript members

So how can I dereference the I'th element of a fixed size array?

like image 974
ja. Avatar asked Jan 13 '16 20:01

ja.


1 Answers

in your case you could try to use something like this ...

// this is tuple with 8 Int values, in your case with 256  Byte (UInt8 ??) values
var t = (1,2,3,4,5,6,7,8)
t.0
t.1
// ....
t.7
func arrayFromTuple<T,R>(tuple:T) -> [R] {
    let reflection = Mirror(reflecting: tuple)
    var arr : [R] = []
    for i in reflection.children {
        // better will be to throw an Error if i.value is not R
        arr.append(i.value as! R)
    }
    return arr
}

let arr:[Int] = arrayFromTuple(t)
print(arr) // [1, 2, 3, 4, 5, 6, 7, 8]

...

let t2 = ("alfa","beta","gama")
let arr2:[String] = arrayFromTuple(t2)
arr2[1] // "beta"
like image 101
user3441734 Avatar answered Sep 19 '22 23:09

user3441734