不能下标类型的值' [Int16]'

时间:2016-01-24 07:32:44

标签: swift

以下是相关代码:

/// Individual audio samples
let samples: [Int16]

/// The rates in Hz
let sampleRate: Int

/// The part of the audio which is a vowel utterance
lazy var vowelPart: Range<Int> = {
    let strongPart = SpeechAnalyzer2.findStrongPartOfSignal(self.samples, withChunks: 300, sensitivity: 0.1)
    let clippedPart = SpeechAnalyzer2.truncateTailsOfRange(strongPart, portion: 0.15)
    return clippedPart
}()

private lazy var vowelSamplesDecimated: [Int16] = {
    let out = SpeechAnalyzer2.decimateSamples(self.samples[self.vowelPart], withFactor: 4)
    return out
}()

底部的out = ...行会显示错误:

  

无法下标类型&#39; [Int16]&#39;

的值

首先,这样的错误消息是如何有效的(当然你可以下标一个数组!)。其次,我如何在本案中解决这个问题?

更新,在接受Nate的回答之后,以下是我如何将下游功能更新为CollectionType上的通用功能以供将来参考:

/// Select the first of every `factor` items from `samples`
class func decimateSamples<T: CollectionType where T.Index: Strideable>(samples: T, withStride stride: T.Index.Stride) -> Array<T.Generator.Element> {
    let selectedSamples = samples.startIndex.stride(to: samples.endIndex, by: stride)
    return selectedSamples.map({samples[$0]})
}

1 个答案:

答案 0 :(得分:3)

您的decimateSamples方法必须以[Int16]数组作为参数。不幸的是,当你下标一个像vowelPart这样的范围的数组时,你得到一个ArraySlice<Int16>,而不是一个相同类型的数组。简单的解决方案是将切片转换为新数组:

... decimateSamples(Array(self.samples[self.vowelPart]), withFactor: 4) ...

最终会复制数组的内容,如果它是一个大数据集,那就不好了。您可以通过对任何类型的Array使其成为通用来使您的函数接受ArraySliceCollectionType

相关问题