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

问题描述 投票:0回答:2

Core Audio Recorder example中,AudioQueueInputCallback函数被写为类Recorder之外的变量绑定。我试图在结构中使用它,但我无法访问任何实例方法。它给出了错误,Instance members cannot be used on type

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错误。

ios swift closures core-audio
2个回答
4
投票

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


0
投票

您可以在懒惰属性的闭包内使用self。所以你应该将'audioQueueInputCallback'定义为懒惰。

© www.soinside.com 2019 - 2024. All rights reserved.