我有一个如下所示的函数:
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'是一个“让...”
虽然我在这里传递的参数都不是let
常量。我为什么要这个?
答案 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 ,所以看起来你不想在这里 - 这不是你的问题(但我当然可以读错了)。