类型'Int'没有下标成员

时间:2015-11-27 12:23:10

标签: ios swift

我写了一个函数:

  func rms16(buffer: Int, bufferSize: Int) -> Float
    {
        let sum: Float = 0.0
        let mySize: Int = bufferSize / sizeof(CShort)
        var buffer_short: Int = buffer
        for var i = 0; i < mySize; i++ {
           sum += buffer_short[i] * 2
        }
        let sqrt1: Float = sqrtf(sum / Float(mySize))
        return (sqrt1) / Float(mySize)
    }

for循环中的上述函数,它显示如下错误:  类型Int没有下标成员

任何人都告诉我如何解决它?

2 个答案:

答案 0 :(得分:1)

buffer_short是整数变量,不是整数数组。 您需要将函数的第一个参数更改为整数数组,如:

func rms16(buffer: [Int], bufferSize: Int) -> Float
{
    let sum: Float   = 0.0
    let mySize: Int  = bufferSize / sizeof(CShort)
    var buffer_short = buffer

    for var i = 0; i < mySize; i++
    {
       sum += buffer_short[i] * 2
    }
    let sqrt1: Float = sqrtf(sum / Float(mySize))
    return (sqrt1) / Float(mySize)
}

答案 1 :(得分:0)

您的注释表明第一个参数应该是字符缓冲区的指针。相应的Swift类型为UnsafePointer<CChar>。另请注意,您乘以2 而不是在您的Swift代码中进行平方,而sum必须是。{1}} 声明为变量

所以你的Swift功能将是

func rms16(buffer: UnsafePointer<CChar>, bufferSize: Int) -> Float
{
    var sum: Float = 0.0
    let mySize = bufferSize / sizeof(CShort)

    // Create a pointer to a buffer of `CShort` elements from the given pointer:
    let buffer_short = UnsafeBufferPointer<CShort>(start: UnsafePointer(buffer), count: mySize)

    for var i = 0; i < mySize; i++ {
        sum += pow(Float(buffer_short[i]), 2)
    }
    let sqrt1  = sqrtf(sum / Float(mySize))
    return (sqrt1) / Float(mySize)
}

求和循环可以减少(!)到:

let sum = buffer_short.reduce(0.0, combine: { $0 + pow(Float($1), 2)} )