8
votes

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?

2
Where is memcpy() function? - Harshal Bhavsar
Does your function need to be able to mutate pChData inside and outside its scope? Or only inside? It isn't clear from your question. Be careful to not use inout if you only need the value to be a variable inside. - Eric Aya
@HarshalBhavsar memcpy()ยด is a function defined in Darwin.C.string`. One of its uses is modifying an MTLBuffer. - Andreas detests censorship

2 Answers

5
votes

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)
}
5
votes

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).