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

Niall Kiddle picture Niall Kiddle · Sep 24, 2017 · Viewed 8.7k times · Source

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")
    }

Answer

joern picture joern · Sep 24, 2017

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)