0

我有两个协议和一个通用结构:

public protocol OneDimensionalDataPoint {
    /// the y value
    var y: Double { get }        
}

public protocol TwoDimensionalDataPoint: OneDimensionalDataPoint {
    /// the x value
    var x: Double { get }
}

public struct DataSet<Element: OneDimensionalDataPoint> {
    /// the entries that this dataset represents
    private var _values: [Element]
    //...implementation
}

extension DataSet: MutableCollection {
    public typealias Element = OneDimensionalDataPoint
    public typealias Index = Int

    public var startIndex: Index {
        return _values.startIndex
    }

    public var endIndex: Index {
        return _values.endIndex
    }

    public func index(after: Index) -> Index {
        return _values.index(after: after)
    }

    public subscript(position: Index) -> Element {
        get{ return _values[position] }
        set{ self._values[position] = newValue }
    }
}

有很多方法DataSetElement适用于TwoDimensionalDataPoint. 所以我做了一个这样的扩展:

extension DataSet where Element: TwoDimensionalDataPoint {
    public mutating func calcMinMaxX(entry e: Element) {
        if e.x < _xMin {
            _xMin = e.x
        }
        if e.x > _xMax {
            _xMax = e.x
        }
    }
}

编译器不喜欢这样,并说:

“DataSet.Element”(又名“OneDimensionalDataPoint”)类型的值没有成员“x”

既然我将 Element 限制TwoDimensionalDataPoint在扩展中,这不应该没问题吗?

4

1 回答 1

1

在我将它放入 Xcode 之后,我能够更好地理解发生了什么,

您的问题是您的类型别名覆盖了您的泛型类型,

将您的通用名称重命名为T并将元素分配给T

public typealias Element = T

或您的类型别名,例如:

public typealias DataElement = OneDimensionalDataPoint

或者只是将 typealias 放在一起。

于 2017-06-18T00:09:26.833 回答