使用语句For编写元组 [英] Use statement For to write in a Tuple

查看:89
本文介绍了使用语句For编写元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码发送midi sysEx.它非常适合发送固定"数据,但是现在我需要发送不同大小的数据.

I use this code to send midi sysEx. It s perfect for sending "fix" data but now i need to send data with different size.

            var midiPacket:MIDIPacket = MIDIPacket()
            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]
            //... 
            //MIDISend...

现在假设我有一个字符串名称"TROLL",但名称可以更改. 我需要这样的东西:

Now imagine i have a String name "TROLL" but the name can change. I need something like this :

            var name:String = "TOTO"
            var nameSplit = name.components(separatedBy: "")
            var size:Int = name.count

            midiPacket.length = UInt16(size)

            for i in 0...size{
                midiPacket.data.i = nameSplit[i]
            }
            //...
            //MIDISend...

但是此代码不起作用,因为我不能在元组中这样使用"i". 如果有人知道该怎么做.

But this code don t work because i can t use "i" like this with a tuple. If someone knows how to do that.

先谢谢了. KasaiJo

Thanks in advance. KasaiJo

推荐答案

C数组作为元组导入到Swift中.但是Swift编译器 保留导入的C结构的内存布局(),因此您可以重新绑定指向元组的指针 指向UInt8的指针:

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] = ...
        }
    }
}

这篇关于使用语句For编写元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆