Swift error: cannot pass immutable value as argument inout: 'pChData' is constant 'let'

I have a function that looks like this:

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 error:

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

Xcode screenshot

Although none of the arguments I pass here are let constants. Why am I getting this?

+6
source share
2 answers

You are trying to access / modify the pChData argument, which you cannot if or until you declare it as an inout . Read more about the inout 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) } 
+3
source

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

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

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

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

+4
source

All Articles