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

How to convert a computed closure property to closure in Swift?

Core Audio Recorder example the AudioQueueInputCallback function is written as a variable binding outside the class Recorder. I am trying to use it inside a struct, but I am not able to access any instance methods. It gives the error, .

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

}

如何在结构中编写 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")
}

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

您可以在惰性闭包中使用 self 属性。所以你应该定义 'audioQueueInputCallback' 为 lazy.

在 Swift 中,如果函数被声明为某种类型的方法,则不能传递用作 C 回调函数的函数。它 必须 是全局的(顶层)或局部的(在另一个函数内)。这就是该示例将其设为全局的原因。