如何在 Swift 中将计算的闭包属性转换为闭包?

jsl*_*oop 1 closures core-audio ios swift

Core Audio Recorder 示例中,AudioQueueInputCallback函数被编写为类之外的变量绑定Recorder。我试图在结构中使用它,但我无法访问任何实例方法。它给出了错误,实例成员不能用于类型

struct Recorder {
    private var log = Logger()
    private let utils = Utils()


    func record() {
        // ...
        AudioQueueNewInput(&recordFormat, audioQueueInputCallback, &recorder, nil, nil, 0, &queue)
    }

    private let audioQueueInputCallback: AudioQueueInputCallback = { (inUserData: UnsafeMutableRawPointer?, inQueue: AudioQueueRef,
                                                                  inBuffer: AudioQueueBufferRef, inStartTime: UnsafePointer<AudioTimeStamp>,
                                                                  inNumPackets: UInt32, inPacketDesc: UnsafePointer<AudioStreamPacketDescription>?) in
        log.debug()   //  <-- error: instance member cannot be used on type Recorder

}
Run Code Online (Sandbox Code Playgroud)

如何audioQueueInputCallback在结构内部写入以便可以在其中访问实例变量?


更新:如果我将 var 更改为 lazy 为:

private lazy var audioQueueInputCallback: AudioQueueInputCallback = {
        (_ inUserData: UnsafeMutableRawPointer?, _ inQueue: AudioQueueRef,
        _ inBuffer: AudioQueueBufferRef, _ inStartTime: UnsafePointer<AudioTimeStamp>,
        _ inNumPackets: UInt32, _ inPacketDesc: UnsafePointer<AudioStreamPacketDescription>?) in
    log.debug("audio queue callback")
}
Run Code Online (Sandbox Code Playgroud)

我收到Closure cannot implicitly capture a mutating self parameter错误。

mat*_*att 5

在 Swift 中,如果函数被声明为类型的方法,则不能传递用作 C 回调函数的函数。它必须是全局(顶级)或本地(在另一个 func 内)。这就是为什么这个例子使它成为一个全球性的。