我尝试在 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/