【问题标题】:Swift Error: Cannot pass immutable value as inout argument: 'pChData' is a 'let' constantSwift 错误:无法将不可变值作为 inout 参数传递:“pChData”是“let”常量
【发布时间】:2016-05-03 17:02:27
【问题描述】:

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

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' 常量

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

【问题讨论】:

  • memcpy() 函数在哪里?
  • 您的函数是否需要能够在 范围内对 pChData 进行变异?还是只在里面?从你的问题看不清楚。如果您只需要将值作为变量inside,请注意不要使用inout。
  • @HarshalBhavsar memcpy()´ is a function defined in Darwin.C.string`。它的用途之一是修改 MTLBuffer。

标签: ios swift function swift2


【解决方案1】:

您正在尝试访问/修改 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)
}

【讨论】:

  • 在 Swift4 中,pChData 应该声明为 'pChData: inout UInt8'。
【解决方案2】:

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

您需要制作一个变量副本(兼容 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)
}

第三个选项,但这不是您要的:将参数设为 inout。但它也会在 func 的 outside 中改变 pchData,所以看起来你不想在这里 - 这不是你的问题(但我当然可能读错了)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多