Swift错误:无法将不可变值作为inout参数传递:'pChData'是'let'常量

7 function ios swift swift2

我有一个如下所示的函数:

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)
}
Run Code Online (Sandbox Code Playgroud)

得到错误:

无法将不可变值作为inout参数传递:'pChData'是'let'常量

Xcode截图

虽然我在这里传递的论点都不是let常数.我为什么要这个?

Par*_*was 5

您正在尝试访问/修改pChData参数,除非您将其声明为inout参数,否则您无法访问/修改参数.在此处详细了解inout参数.所以尝试使用以下代码.

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)
}
Run Code Online (Sandbox Code Playgroud)


aya*_*aio 5

传递给函数的参数默认情况下在函数内是不可变的.

你需要制作一个变量副本(兼容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)
}
Run Code Online (Sandbox Code Playgroud)

或者,使用Swift 2,您可以添加var参数:

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)
}
Run Code Online (Sandbox Code Playgroud)

第三种选择,但这不是你所要求的:使论证成为不足.但它也会在func 之外改变pchData ,所以看起来你不想在这里 - 这不是你的问题(但我当然可以读错了).