【问题标题】:How to convert a computed closure property to closure in Swift?如何在 Swift 中将计算的闭包属性转换为闭包?
【发布时间】:2019-07-24 23:48:52
【问题描述】:

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 更改为惰性:

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


【解决方案1】:

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

【讨论】:

【解决方案2】:

你可以在惰性属性的闭包中使用 self。因此,您应该将“audioQueueInputCallback”定义为惰性。

【讨论】:

  • 它给出了Closure cannot implicitly capture a mutating self parameter。错误。我已更新问题以反映更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多