xcodeconditional-statementsoption-typespeechavaudioengine

(Swift) Initializer for conditional binding must have Optional type, not 'AVAudioInputNode'


I am trying to create a speech to text function and I am getting the error:

Initializer for conditional binding must have Optional type, not 'AVAudioInputNode'

guard let inputNode = audioEngine.inputNode else {
        fatalError("Audio engine has no input node")
    }

Solution

  • AVAudioEngine's inputNode property is not an optional. The Audio Engine creates a singleton on demand when inputNode is first accessed. It cannot be nil and because of that the guard does not make sense.

    So, just remove the guard and use audioEngine.inputNode as it is. It cannot be nil.

    You still have to make sure that the inputNode is connected to something before using it:

    Check the input format of input node (specifically, the hardware format) for a non-zero sample rate and channel count to see if input is enabled.

    (from Apple's Documentation)