Search code examples
swiftreferenceswift3avfoundationopaque-pointers

Initialize an AudioConverterRef Swift 3.0


var audioConverter : AudioConverterRef = nil
audioConverter = AudioConverterRef.init()

So basically I have the code above found from this StackOverflow answer that is using a previous version of Swift. Now in Swift 3.0 however the above initializer for AudioConverterRef is not available.

I noticed that the AudioConverterRef is a reference to an audio converter object, which I suppose is an AVAudioConverter.

So, the short question would be how would I write the above code in Swift 3.0? And the longer question would be what are the uses of creating an AudioConverterRef that just references an AVAudioConverter? Aren't all variables just reference to an object?


Solution

  • As you know, AudioConverterRef was just a typealias of COpaquePointer in Swift 2.x and is a typealias of OpaquePointer in Swift 3.

    But one significant change you should realize is not the name but the feature which is common to all pointers in Swift 3:

    • In Swift 3, pointer types cannot contain nil, and if you want to store nil to a pointer type variable, you need to declare it as an Optional pointer. (SE-0055)

    So, for the short question:

    var audioConverter : AudioConverterRef? = nil
    audioConverter = nil
    

    And for the longer one:

    The type AudioConverterRef is declared as:

    typedef struct OpaqueAudioConverter *   AudioConverterRef;
    

    And the type struct OpaqueAudioConverter is a hidden C-struct. It is not just referencing AVAudioConverter, but may be holding some info to work with C-function based AudioConverter APIs. Its properties may be held in more primitive forms than similar properties in AVAudioConverter.

    You have no need to work with AudioConverterRef, if all functionalities you need is available in AVAudioConverter.