swift中的编译器错误indexOf()

时间:2016-04-20 08:29:42

标签: swift

所以我有这样的功能:

    var localIndices: [ChartHighlight] = []

    for globalHighlight in globalIndices
    {
        if let globalSet = data?.dataSets[globalHighlight.dataSetIndex]
        {
            if globalSet.dynamicType === dataSetType
            {
                let chartData = getChartData(dataSetType)

                if (chartData == nil)
                {
                    return globalIndices
                }

                let localdataSetIndex = chartData!.dataSets.indexOf(globalSet)
                if (localdataSetIndex != nil)
                {
                    localIndices.append(ChartHighlight(xIndex: globalHighlight.xIndex, dataSetIndex: localdataSetIndex!, stackIndex: globalHighlight.stackIndex))
                }
            }
            else
            {
                return globalIndices
            }
        }
    }

编译器抱怨

let localdataSetIndex = chartData!.dataSets.indexOf(globalSet)

  

无法转换类型' IChartDataSet'的值预期参数类型' @noescape(IChartDataSet)抛出 - >布尔'

我很困惑为什么我不能将indexOf()用于[IChartDataSet]。这与chartData!.dataSets[IChartDataset]IChartDatasetprotocol类型相关吗? 我没有看到swift doc提到这个,或者我错过了它......

1 个答案:

答案 0 :(得分:3)

要将indexOf方法与元素一起用作输入参数,dataSets的元素类型IChartDataSet必须符合Equatable协议,如{{1}所示扩展名定义:

CollectionType

或者您可以改为使用谓词闭包:

    extension CollectionType where Generator.Element : Equatable {
       /// Returns the first index where `value` appears in `self` or `nil` if
        /// `value` is not found.
        ///
        /// - Complexity: O(`self.count`).
        @warn_unused_result
        public func indexOf(element: Self.Generator.Element) -> Self.Index?
    }