11

I have a function that looks like the following:

func receivedData(pChData: UInt8, andLength len: CInt) {
    var receivedData: Byte = Byte()
    var receivedDataLength: CInt = 0

    memcpy(&receivedData, &pChData, Int(len));  // Getting the error here
    receivedDataLength = len
    AudioHandler.sharedInstance.receiverAudio(&receivedData, WithLen: receivedDataLength)
}

Getting the error:

Cannot pass immutable value as inout argument: 'pChData' is a 'let' constant

Xcode screenshot

Though none of the arguments which I am passing here are let constants. Why am I getting this?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

8

Arguments passed to a function are immutable inside the function by default.

You need to make a variable copy (Swift 3 compatible):

func receivedData(pChData: UInt8, andLength len: CInt) {
    var pChData = pChData
    var receivedData: Byte = Byte()
    var receivedDataLength: CInt = 0

    memcpy(&receivedData, &pChData, Int(len));  // Getting the error here
    receivedDataLength = len
    AudioHandler.sharedInstance.receiverAudio(&receivedData, WithLen: receivedDataLength)
}

or, with Swift 2, you can add var to the argument:

func receivedData(var pChData: UInt8, andLength len: CInt) {
    var receivedData: Byte = Byte()
    var receivedDataLength: CInt = 0

    memcpy(&receivedData, &pChData, Int(len));  // Getting the error here
    receivedDataLength = len
    AudioHandler.sharedInstance.receiverAudio(&receivedData, WithLen: receivedDataLength)
}

Third option, but that's not what you're asking for: make the argument an inout. But it will also mutate pchData outside of the func, so it looks like you don't want this here - this is not in your question (but I could have read that wrong of course).

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
6

You are trying to access/modify pChData argument, which you can't unless or until you declare it as inout parameter. Learn more about inout parameter here. So try with the following code.

func receivedData(inout pChData: UInt8, andLength len: CInt) {
    var receivedData: Byte = Byte()
    var receivedDataLength: CInt = 0

    memcpy(&receivedData, &pChData, Int(len));
    receivedDataLength = len
    AudioHandler.sharedInstance.receiverAudio(&receivedData, WithLen: receivedDataLength)
}
Partho Biswas
  • 2,290
  • 1
  • 24
  • 39