Swift错误:无法将不可变值作为inout参数传递:' pChData'是一个“让...”不变

时间:2016-05-03 17:02:27

标签: ios swift function 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)
}

获取错误:

  

不能将不可变值作为inout参数传递:' pChData'是一个“让...”

Xcode screenshot

虽然我在这里传递的参数都不是let常量。我为什么要这个?

2 个答案:

答案 0 :(得分:5)

您正在尝试访问/修改pChData参数,除非或直到您将其声明为inout参数,否则您无法参考。详细了解inout参数here。请尝试使用以下代码。

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

答案 1 :(得分: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)
}

或者,使用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)
}

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