我在Objective-C(使用Audio Toolbox框架)中有以下代码,我正在尝试将其转换为Swift:
MusicTimeStamp timeStamp;
MusicEventType eventType;
const void *eventData;
UInt32 eventDataSize;
//MusicEventIteratorGetEventInfo is declared in Audio Toolbox framework as this:
//OSStatus MusicEventIteratorGetEventInfo ( MusicEventIterator inIterator, MusicTimeStamp *outTimeStamp, MusicEventType *outEventType, const void **outEventData, UInt32 *outEventDataSize );
MusicEventIteratorGetEventInfo(anIterator, &timeStamp, &eventType, &eventData, &eventDataSize);
switch (eventType){
case kMusicEventType_MIDINoteMessage:
//extract info from eventData assuming it's a MIDINoteMessage.
UInt8 channel = ((MIDINoteMessage *) eventData)->channel
UInt8 note = ((MIDINoteMessage *) eventData)->note
UInt8 velocity = ((MIDINoteMessage *) eventData)->velocity
Float32 duration = ((MIDINoteMessage *) eventData)->duration
case kMusicEventType_MIDIChannelMessage:
//extract info from eventData assuming it's a MIDIChannelMessage.
//case ..., etc.
}
当在Swift中重写它时,我无法弄清楚如何从“const void * eventData”部分获取数据,尽管阅读了关于不安全指针的Apple文档(他们的例子似乎都与提取无关)以这种方式来自不安全指针的数据)。这就是我到目前为止所做的,但我在switch语句应该是什么方面迷失了:
var timeStamp: MusicTimeStamp = 0
var eventType: MusicEventType = 0
var eventData: UnsafeMutablePointer<UnsafePointer<Void>> = nil
var eventDataSize: UInt32 = 0
MusicEventIteratorGetEventInfo(iterator, &timeStamp, &eventType, eventData, &eventDataSize)
//what would simplest equivalent switch statement be?
任何帮助都将不胜感激 - 谢谢。
答案 0 :(得分:4)
只要你知道你在那个不安全的指针中躲藏了什么类型的数据,你总是可以使用每个变体的各种构造函数来在指针之间进行转换。如果你牢记这一点,你的例子很容易翻译:
import AudioToolbox
var timeStamp : MusicTimeStamp = 0
var eventType : MusicEventType = 0
var eventData : UnsafePointer<Void> = nil
var eventDataSize : UInt32 = 0;
MusicEventIteratorGetEventInfo(anIterator, &timeStamp, &eventType, &eventData, &eventDataSize);
switch (eventType){
case kMusicEventType_MIDINoteMessage:
let data = UnsafePointer<MIDINoteMessage>(eventData)
let channel = data.memory.channel
let note = data.memory.note
let velocity = data.memory.velocity
let duration = data.memory.duration
case kMusicEventType_MIDIChannelMessage:
//extract info from eventData assuming it's a MIDIChannelMessage.
//case ..., etc.
}