我写了一个函数:
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
没有下标成员
任何人都告诉我如何解决它?
答案 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)} )