c - 如何在 Swift 中实现 AudioServicesSystemSoundCompletionProc?

标签 c xcode swift

我尝试在 Xcode 中使用 Swift 为 AudioServicesAddSystemSoundCompletion 中的参数创建 AudioServicesSystemSoundCompletionProc 实例,但失败了。

这是我到目前为止所得到的

func completionCallback(ssID:SystemSoundID,clientData:UnsafeMutablePointer<Void>) -> Void {

}

var foo:(ssID:SystemSoundID,clientData:UnsafeMutablePointer<Void>) -> Void = completionCallback;

AudioServicesAddSystemSoundCompletion(soundID, nil, nil, foo, nil);

我在一些解释如何在 Swift 中编写等效的 C 函数指针的指南的帮助下写了这篇文章,但这引发了这个错误:

'(ssID: SystemSoundID, clientData: UnsafeMutablePointer<Void>) -> Void' is not convertible to 'AudioServicesSystemSoundCompletionProc'

文档显示了 Objective-C 声明:

typedef void (*AudioServicesSystemSoundCompletionProc) ( SystemSoundID ssID, void *clientData );

这是使用 Xcode 时显示的声明:

typealias AudioServicesSystemSoundCompletionProc = CFunctionPointer<((SystemSoundID, UnsafeMutablePointer<Void>) -> Void)>

我不确定如何在 Swift 中正确实现 AudioServicesSystemSoundCompletionProc。

最佳答案

从 Swift 2.0 开始,您可以将其作为闭包来实现。

AudioServicesAddSystemSoundCompletion(soundID, nil, nil, { (soundID, clientData) -> Void in

    // Your completion callback...                            
    AudioServicesDisposeSystemSoundID(soundID)

}, nil) 

进一步info from Apple (向下滚动到函数指针):

C function pointers are imported into Swift as closures

关于c - 如何在 Swift 中实现 AudioServicesSystemSoundCompletionProc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823405/

相关文章:

c - c中的文件处理

c - 使用 unsigned long 类型进行位移会产生错误的结果

c - Windows 创建动态数量的链接

ios - 将存档保存到文档文件夹

iphone - 使用 Storyboard以编程方式设置 UITabBarItem 图标?

Swift 泛型(类型替换?)

使用 OpenSSL 内存 BIO 写入和读取以空字符结尾的字符串的正确方法

xcode - 如何使 Xcode 使用 “User headers search paths” 正确找到 header ?

swift - 如何以编程方式在自定义 uiView swift 中创建 UIlabel

ios - Swift:未识别 UITextField