Use statement For to write in a Tuple

↘锁芯ラ 提交于 2019-12-06 02:06:27

C arrays are imported to Swift as tuples. But the Swift compiler preserves the memory layout of imported C structures (source), therefore you can rebind a pointer to the tuple to an pointer to UInt8:

withUnsafeMutablePointer(to: &midiPacket.data) {
    $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: midiPacket.data)) {
        dataPtr in // `dataPtr` is an `UnsafeMutablePointer<UInt8>`

        for i in 0..<size {
            dataPtr[i] = ...
        }
    }
}

I don't know any proper way to do that, as tuples are compound type and can't be extended to add additional functionality.

One way of improving it I can think about is extracting it to a func like:

    func setMidiPacket(_ midi: MIDIPacket fromArray array: [ProbablyInt]) {
        midiPacket.length = 6
        midiPacket.data.0 = data[0]
        midiPacket.data.1 = data[1]
        midiPacket.data.2 = data[2]
        midiPacket.data.3 = data[3]
        midiPacket.data.4 = data[4]
        midiPacket.data.5 = data[5]
    }

setMidiPacket(midi, data)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!