Caz
Caz

Reputation: 19

Unable to understand the certain operator in Swift

I have been changing some SWIFT code into OBJECTIVE-C, and I am stuck at certain part of the code, where I am unable to understand if it is a condition or something else.

Following is the code and I am stuck on 9th line stating :

if let channel1Buffer = buffer.floatChannelData?[0]

What I do not understand here is the above if condition is checking if "buffer.floatChannelData" is null, and then proceeding to get the first index, or is it something else.

input.installTap(onBus: 0, bufferSize:4096, format:format, block: { [weak self] buffer, when in
    guard let this = self else {
        return
    }

    print("Buffer Float Channel Data: ", buffer.floatChannelData as Any);

    **if let channel1Buffer = buffer.floatChannelData?[0]** { 
        print("channel1Buffer: ", channel1Buffer);

        /// encode PCM to mp3
        let frameLength = Int32(buffer.frameLength) / 2;

        print("frameLength: ", frameLength);

        let bytesWritten = lame_encode_buffer_interleaved_ieee_float(this.lame, channel1Buffer, frameLength, this.mp3buf, 4096);
        // `bytesWritten` bytes stored in this.mp3buf now mp3-encoded
        print("\(bytesWritten) encoded");

        this.file.append(this.mp3buf, length: Int(bytesWritten));

        // @TODO: send data, better to pass into separate queue for processing
    }
})

Upvotes: 1

Views: 83

Answers (2)

Paulius Vindzigelskis
Paulius Vindzigelskis

Reputation: 2181

Let's take it part by part - buffer.floatChannelData?[0]

buffer has property named floatChannelData which is optional so it has ? at the end. then it takes that optional which accepts subscription [0] which also returns optional value. So it continues inside {} only if floatChannelData is not nil AND it's first value is not nil

Your Objc should look like

float *const *channelData = [buffer floatChannelData]; 
if (channelData) {
    float *channel1Buffer = channelData[0]; //this might crash if channelData is empty
    ...

Upvotes: 1

Tommy Pedersen
Tommy Pedersen

Reputation: 13

The line tries to assign the variable channel1Buffer the value of buffer.floatChannelData[0], and the code within {} is only executed if that assignment is successful. It may for instance fail if buffer.floatChannelData is nil or buffer.floatChannelData[0] is nil.

Upvotes: 0

Related Questions